├── .github ├── ISSUE_TEMPLATE │ └── create-an-issue.md └── pull_request_template.md ├── 1854. Maximum Population Year.cpp ├── C++ ├── 1. TwoSum.cpp ├── 10. Regular Expression Matching.cpp ├── 1007.MinimumDominoRotationsForEqualRow.cpp ├── 101. SymmetricTree.cpp ├── 1011. Capacity To Ship Packages Within D Days.cpp ├── 1015. Smallest Integer Divisible by K.cpp ├── 102. BinaryTreeLevelOrderTraversal.cpp ├── 1022. SumofRootToLeafBinaryNumbers.cpp ├── 1023. CammelCaseMatching.cpp ├── 1024. VideoStitching.cpp ├── 1025. DivisorGame.cpp ├── 1026. Maximum Difference Between Node and Ancestor.cpp ├── 1029. TwoCityScheduling.cpp ├── 103. BinaryTreeZigzagLevelOrderTraversal.cpp ├── 104. MaximumDepthOfBinaryTree.cpp ├── 1046. Last Stone Weight.cpp ├── 1049. LastStoneWeightII.cpp ├── 105.ConstructBinaryTreefromPreorderandInorderTraversal.cpp ├── 1051. HeightChecker.cpp ├── 107. BinaryTreeLevelOrderTraversalII.cpp ├── 108. ConvertSortedArraytoBinarySearchTree.cpp ├── 1095. Find in Mountain Array.cpp ├── 11. ContainerWithMostWater.cpp ├── 1108. DefangingAnIPAddress.cpp ├── 111.MinimumDepthOfBinaryTree.cpp ├── 112. PathSum.cpp ├── 1123. Lowest Common Ancestor of Deepest Leaves.cpp ├── 113.PathSumII.cpp ├── 1134.ArmstrongNumber.cpp ├── 1137. N-th Tribonacci Number.cpp ├── 115. Distinct Subsequences.cpp ├── 116. PopulatingNextRightPointersInEachNode.cpp ├── 117.PopulatingNextRightPointersInEachNodeII.cpp ├── 1170. CompareStringsByFrequencyOfTheSmallestCharacter.cpp ├── 1171. RemoveZeroSumConsecutiveNodesInLinkedList.cpp ├── 1172. DinnerPlateStacks.cpp ├── 118. PascalTriangle.cpp ├── 12. Integer to Roman ├── 1202.SmallestStringWithSwaps.cpp ├── 1209.RemoveAllAdjacentDuplicatesInStringII.cpp ├── 121. BestTimetoBuyandSellStock.cpp ├── 1217. Minimum Cost to Move Chips to The Same Position.cpp ├── 1221. SplitaStringInBalancedStrings.cpp ├── 1232.CheckIfItIsAStraight Line.cpp ├── 124. Binary_Tree_Maximum.cpp ├── 1249.MinimumRemoveToMakeValidParentheses.cpp ├── 125. ValidPalindrome.cpp ├── 1260.Shift2DGrid.cpp ├── 1266. Minimum Time Visiting All Points.cpp ├── 127. Word Ladder.cpp ├── 1277. CountSquareSubmatricesWithAllOnes.cpp ├── 128. LongestConsecutiveSequence.cpp ├── 1281.SubtractTheProductAndSumOfDigitsOfAnInteger.cpp ├── 1283. Find the Smallest Divisor Given a Threshold.cpp ├── 1288. RemoveCoveredIntervals.cpp ├── 129. Sum Root to Leaf Numbers.cpp ├── 1290. Convert Binary Number in a Linked List to Integer.cpp ├── 1295. Find Numbers with Even Number of Digits.cpp ├── 13. Roman_To_Integer.cpp ├── 1304. FindNUniqueIntegersSumUpToZero.cpp ├── 1305. AllElementsinTwoBinarySearchTrees.cpp ├── 1306. Jump Game III.cpp ├── 1309.DecryptStringFromAlphabetToIntegerMapping.cpp ├── 1310. XORQueriesOfASubarray.cpp ├── 1313. Decompress Run-Length Encoded List.cpp ├── 1329.SortTheMatrixDiagonally.cpp ├── 1337.TheKWeakestRowsInAMatrix.cpp ├── 134. GasStation.cpp ├── 1342. NumberofStepstoReduceaNumbertoZero.cpp ├── 135. Candy.cpp ├── 1351. Count Negative Numbers in a Sorted Matrix.cpp ├── 1356.SortIntegersByTheNumberOf1Bits.cpp ├── 1359.CountAllValidPickupandDeliver Options.cpp ├── 136. Single Number.cpp ├── 1363. LargestMultipleOfThree.cpp ├── 1365. SmallestNumberThanCurrentNumber.cpp ├── 1379. FindaCorrespondingNodeofaBinaryTreeinaCloneofThatTree.cpp ├── 138.CopyListWithRandomPointer.cpp ├── 1389. Create Target Array in the Given Order.cpp ├── 139. WordBreak.cpp ├── 1396.DesignUndergroundSystem.cpp ├── 14. LongestCommonPrefix.cpp ├── 1403. Minimum Subsequence in Non-Increasing Order.cpp ├── 1406. StoneGameIII.cpp ├── 1408. StringMatchingInAnArray.cpp ├── 141. Linked List Cycle.cpp ├── 142. LinkedListCycle.cpp ├── 143. Reorder List.cpp ├── 1431. KidsWithTheGreatesNumberOfCandies.cpp ├── 145.BinaryTreePostorderTraversal.cpp ├── 146. LRUCache.cpp ├── 1463. CherryPickup2.cpp ├── 1464. MaximumProductOfTwoElementsInAnArray.cpp ├── 1470. ShuffleTheArray.cpp ├── 1476. Subrectangle Queries.cpp ├── 148. SortList.cpp ├── 1480. Running Sum of 1d Array.cpp ├── 1486. XOR Operation in an Array.cpp ├── 1491.AverageSalaryExcludingTheMinimumAndMaximumSalary.cpp ├── 1492.kthfactor.cpp ├── 1496.PathCrossing.cpp ├── 15. 3Sum.cpp ├── 1502.CanMakeArithmeticProgressionFromSequence.cpp ├── 151.ReverseWordsInAString.cpp ├── 1510. StoneGameIV.cpp ├── 1512. NumberofGoodPairs.cpp ├── 152. MaximumProductSubarray.cpp ├── 1520.MaximumNumberOfNonOverlappingSubstrings.cpp ├── 1523.CountOddNumbersInAnIntervalRange.cpp ├── 1525. NumberOfGoodWaysToSplitAString.cpp ├── 1528. Shuffle String.cpp ├── 153.FindMinimuminRotatedSortedArray.cpp ├── 1539. KthMissingPositiveNumber.cpp ├── 154. FindMinimumInRotatedSortedArrayII.cpp ├── 1544. MakeTheStringGreat.cpp ├── 155. Min Stack.cpp ├── 1551. MinimumOperationsToMakeArrayEqual.cpp ├── 1557.MinimumNumberOfVerticesToReachAllNodes.cpp ├── 1561. MaximumNumberOfCoinsYouCanGet.cpp ├── 1563. StoneGameV.cpp ├── 1572. Matrix Diagonal Sum.cpp ├── 1588. SumofAllOddLengthSubarrays.cpp ├── 1589. MaximumSumObtainedOfAnyPermutation.cpp ├── 1603. Design Parking System.cpp ├── 1605. FindValidMatrixGivenRowAndColumnSums.cpp ├── 1608. Special Array With X Elements Greater Than or Equal X.cpp ├── 1610. MaximumNumberOfVisiblePoints.cpp ├── 1614. MaximumNestingDepthOfTheParentheses.cpp ├── 162.FindPeakElement.cpp ├── 1626. Best Team With No Conflicts.cpp ├── 1627. Graph Connectivity With Threshold.cpp ├── 1629. SlowestKey.cpp ├── 164. Maximum Gap.cpp ├── 1646. Get Maximum in Generated Array.cpp ├── 1647. Minimum Deletions to Make Character Frequencies Unique.cpp ├── 1663.SmallestStringWithAGivenNumericValue.cpp ├── 167. TwoSumII-InputArrayIsSorted.cpp ├── 1672.RichestCustomerWealth.cpp ├── 1678.GoalParserInterpretation.cpp ├── 1679.MaxNumberOfK-SumPairs.cpp ├── 169. MajorityElement.cpp ├── 169. Majority_Element.cpp ├── 17. LetterCombinationsOfAPhoneNumber.cpp ├── 1721.SwappingNodesInALinkedList.cpp ├── 173.BinarySearchTreeIterator.cpp ├── 1768.MergeStringsAlternately.cpp ├── 1773.CountItemsMatchingARule.cpp ├── 1779.FindNearestPointThat HasTheSame XorYCoordinate.cpp ├── 179.Largest Number.cpp ├── 1790.CheckIfOneStringSwapCanMakeStringsEqual.cpp ├── 18. FourSum.cpp ├── 1822.SignOfTheProductOfAnArray.cpp ├── 187. RepeatedDNASequences.cpp ├── 189. Rotated_Array.cpp ├── 19.RemoveNthNodeFromEndofList.cpp ├── 191.NumberOf1Bits.cpp ├── 1929. Concatenation of Array.cpp ├── 198. HouseRobber.cpp ├── 199. BinaryTreeRightSideView.cpp ├── 2. AddTwoNumbers.cpp ├── 20. ValidParenthesis.cpp ├── 200. NumberOfIslands.cpp ├── 201. BitwiseANDofNumbersRange.cpp ├── 202. HappyNumber.cpp ├── 203. RemoveLinkedListElements.cpp ├── 204.CountPrimes.cpp ├── 206.ReverseLinkedList.cpp ├── 21. MergeTwoSortedLists.cpp ├── 2139.MinimumMovesToReachTargetScore.cpp ├── 216.CombinationSumIII.cpp ├── 217. ContainsDuplicate.cpp ├── 22. GenerateParenthesis.cpp ├── 220. ContainsDuplicateIII.cpp ├── 221. Maximal Square.cpp ├── 225. Implement Stack Using Queues.cpp ├── 23. Merge_k_Sorted_Lists.cpp ├── 230.KthSmallesElementInABST.cpp ├── 231. PowerOfTwo.cpp ├── 232. Implement Queue Using Stacks.cpp ├── 235. Lowest Common Ancestor of a Binary Search Tree.cpp ├── 236. LowestCommonAncestorOfABinaryTree.cpp ├── 239. SlidingWindowMaximum.cpp ├── 24. Swap_Nodes_In_Pairs.cpp ├── 240.SearchA2DMatrixII.cpp ├── 242.ValidAnagram.cpp ├── 25. Reverse Nodes in k-group.cpp ├── 26. RemoveDuplicatesFromSortedArray.cpp ├── 268. MissingNumber.cpp ├── 27. RemoveElement.cpp ├── 28. Implement strStr().cpp ├── 283. MoveZeroes.cpp ├── 284.PeekingIterator.cpp ├── 287. Find the Duplicate Number.cpp ├── 289. GameOfLife.cpp ├── 29.DivideTwoIntegers.cpp ├── 295. FindMedianfromDataStream.cpp ├── 297. SerializeAndDeserializeBinaryTree.cpp ├── 299. Bulls_and_Cows.cpp ├── 3. LongestSubstringWithoutRepeatingCharacters.cpp ├── 300. LongestIncreasingSubsequence.cpp ├── 303.RangeSumQueryImmutable.cpp ├── 31. NextPermutation.cpp ├── 312. BurstBalloons.cpp ├── 316.RemoveDuplicateLetters.cpp ├── 319. BulbSwitcher.cpp ├── 32. LongestValidParenthesis.cpp ├── 322. CoinChange.cpp ├── 326. PowerOfThree.cpp ├── 33.SearchInRotatedSortedArray.cpp ├── 334. Increasing Triplet Subsequence.cpp ├── 337. House Robber III.cpp ├── 338. CountingBits.cpp ├── 34. FindFirstAndLastPositionOfElementinSortedArray.cpp ├── 341. FlattenNestedListIterator.cpp ├── 342.PowerOfFour.cpp ├── 344.ReverseString.cpp ├── 347. TopKFrequentElements.cpp ├── 35. SearchInsertPosition.cpp ├── 350.IntersectionOfTwoArraysII.cpp ├── 355. DesignTwitter.cpp ├── 36. ValidSudoku.cpp ├── 367. ValidPerfectSquare.cpp ├── 38. CountAndSay.cpp ├── 380. Insert Delete GetRandom O(1).cpp ├── 383. RansomNote.cpp ├── 389. FindtheDifference.cpp ├── 39. Combination Sum.cpp ├── 392. IsSubsequence.cpp ├── 394. Decode String.cpp ├── 395. Longest Substring with At Least K Repeating Characters.cpp ├── 396. RotateFunction.cpp ├── 399.EvaluateDivision.cpp ├── 4. MedianOfTwoSortedArrays.cpp ├── 40.CombinationSumII.cpp ├── 404.SumOfLeftLeaves.cpp ├── 405. ConvertNumberToHexadecimal.cpp ├── 41. FirstMissingPositive.cpp ├── 410.SplitArrayLargestSum.cpp ├── 413.ArithmeticSlices.cpp ├── 414.PartitionEqualSubsetSum.cpp ├── 42. TrappingRainWater.cpp ├── 437.PathSumIII.cpp ├── 438. FindAllAnagramsInAString.cpp ├── 44. WildcardMatching.cpp ├── 445. Add Two Numbers II.cpp ├── 448. Find_All_Numbers_Disappeared_in_an_Array.cpp ├── 451. Sort Characters By Frequency.cpp ├── 458. Poor Pigs.cpp ├── 46. Permutations.cpp ├── 461. HammingDistance.cpp ├── 47. Permutations II.cpp ├── 476. NumberComplement.cpp ├── 477. TotalHammingDistance.cpp ├── 48. RotateImage.cpp ├── 49. Group_Anagrams.cpp ├── 496.NextGreaterElementI.cpp ├── 5. LongestPalindromicSubstring.cpp ├── 50. Pow-function.cpp ├── 500. KeyboardRow.cpp ├── 504. Base 7.cpp ├── 506. Relative Ranks.cpp ├── 509.FibonacciNumber.cpp ├── 51.NQueens.cpp ├── 53. Maximum Subarray.cpp ├── 532. K-diffPairsInAnArray.cpp ├── 535.EncodeAndDecodeTinyURL.cpp ├── 538.ConvertBSTtoGreaterTree.cpp ├── 54. SpiralMatrix.cpp ├── 540. SingleElementInASortedArray.cpp ├── 542. 01Matrix.cpp ├── 543. DiameterOfBinaryTree.cpp ├── 547. FriendCircles.cpp ├── 559. MaximumDepthOfN-aryTree.cpp ├── 56. MergeIntervals.cpp ├── 561. Array Partition I.cpp ├── 563. Binary Tree Tilt.cpp ├── 566.ReshapeTheMatrix.cpp ├── 581.ShortestUnsortedContinuousSubarray.cpp ├── 589.N-aryTreePreorderTraversal.cpp ├── 59.SpiralMatrixII.cpp ├── 593. Valid Square.cpp ├── 6. ZigzagConversion.cpp ├── 605. CanPlaceFlowers.cpp ├── 606. ConstructStringFromBinaryTree.cpp ├── 61. RotateList.cpp ├── 617. MergeTwoBinaryTrees.cpp ├── 62.UniquePaths.cpp ├── 621. Task Scheduler.cpp ├── 633. SumOfSquareNumbers.cpp ├── 637.AverageOfLevelsInBinaryTree.cpp ├── 639. DecodeWaysII.CPP ├── 65. ValidNumber.cpp ├── 654. MaximumBinaryTree.cpp ├── 66. PlusOne.cpp ├── 665. Non-decreasingArray.cpp ├── 669.TrimABinarySearchTree.cpp ├── 67. AddBinary.cpp ├── 680.ValidPalindromeII.cpp ├── 682.BaseballGame.cpp ├── 693. BinaryNumberwithAlternatingBits.cpp ├── 7. Reverse_Integer.cpp ├── 7.ReverseInteger.cpp ├── 700.SearchInABinarySearchTree.cpp ├── 701. InsertIntoABinarySearchTree.cpp ├── 703.KthLargestElementInAStream.cpp ├── 704. BinarySearch.cpp ├── 705.DesignHashSet.cpp ├── 706.DesignHashMap.cpp ├── 709. To Lower Case.cpp ├── 71.SimplifyPath.cpp ├── 714. BestTimetoBuyandSellStockwithTransactionFee.cpp ├── 72. Edit_Distance.cpp ├── 720.LongestWordInDictionary.cpp ├── 73. SetMatrixZeroes.cpp ├── 730. CountDifferentPalindromicSubsequences.cpp ├── 733. FloodFill.cpp ├── 735. Asteroid Collision.cpp ├── 74. SearchA2DMatrix.cpp ├── 740.DeleteAndEarn.cpp ├── 744. FindSmallestLetterGreaterThanTarget.cpp ├── 746. MinCostClimbingStairs.cpp ├── 75.SortColors.cpp ├── 763. Partition Labels.cpp ├── 765. Couples Holding Hands.cpp ├── 766. Toeplitz Matrix.cpp ├── 77. Combinations.cpp ├── 771. JewelsandStones.cpp ├── 78. SubsetsOfAGivenArray.cpp ├── 780. ReachingPoints.cpp ├── 785.IsGraphBipartite.cpp ├── 79.WordSearch.cpp ├── 799. Champagne Tower.cpp ├── 8. StringToInteger(atoi).cpp ├── 80. RemoveDuplicatesfromSortedArrayII.cpp ├── 804. UniqueMorseCodeWords.cpp ├── 805. SplitArrayWithSameAverage.cpp ├── 81. Search in Rotated Sorted Array II.cpp ├── 812. LargestTriangleArea.cpp ├── 82. RemoveDuplicatesFromSortedListII.cpp ├── 829. ConsecutiveNumbersSum.cpp ├── 83. RemoveDuplicatesFromSortedList.cpp ├── 832. Flipping an Image.cpp ├── 834. Sum of Distances in Tree.cpp ├── 84. LargestRectangleInHistogram.cpp ├── 844. BackspaceStringCompare.cpp ├── 845. LongestMountainInArray.cpp ├── 85. Maximal_Rectangle.cpp ├── 852. Peak Index in a Mountain Array.cpp ├── 855. ExamRoom.cpp ├── 856. Score of Parentheses.cpp ├── 858. Mirror Reflection.cpp ├── 859. BuddyStrings.cpp ├── 860. LemonadeChange.cpp ├── 867. TransposeMatrix.cpp ├── 87. ScrambleString.cpp ├── 871. MinimumNumberOfRefuelingStops.cpp ├── 875. KokoEatingBananas.cpp ├── 876. Middle of the Linked List.cpp ├── 88. MergeSortedArray.cpp ├── 881.BoatsToSavePeople.cpp ├── 887. SuperEggDrop.cpp ├── 89. GrayCode.cpp ├── 890. Find and Replace Pattern.cpp ├── 895. MaximumFrequencyStack.cpp ├── 896. MonotonicArray.cpp ├── 897.IncreasingOrderSearchTree.cpp ├── 9. Palindrome Number.cpp ├── 904.FruitIntoBaskets.cpp ├── 905. SortArrayByParity.cpp ├── 91. DecodeWays.cpp ├── 917. ReverseOnlyLetters.cpp ├── 921. MinimumAddToMakeParenthesesValid.cpp ├── 922. SortArrayByParityII.cpp ├── 923.3SumWithMultiplicity.cpp ├── 925. Long Pressed Name.cpp ├── 927. ThreeEqualParts.cpp ├── 938. RangeSumofBST.cpp ├── 940. DistinctSubseqII.cpp ├── 941. ValidMountainArray.cpp ├── 942. DIStringMatch.cpp ├── 944. DeleteColumnsToMakeSorted.cpp ├── 946.ValidateStackSequences.cpp ├── 949. Largest Time for Given Digits.cpp ├── 953. VerifyingAnAlienDictionary.cpp ├── 961. N-RepeatedElementInSize2NArray.cpp ├── 973. KClosestPointstoOrigin.cpp ├── 976.LargestPerimeterTriangle.cpp ├── 977. SquaresOfASortedArray.cpp ├── 99.RecoverBinarySearchTree.cpp ├── 991.BrokenCalculator.cpp ├── 992. Subarrays with K Different Integers.cpp ├── 997. FindTheTownJudge.cpp └── anagram.cpp ├── CONTRIBUTING.md ├── Java ├── 1. Two Sum.java ├── 101. SymmetricTree.java ├── 1019. NextGreaterNodeInLinkedList.java ├── 1029. TwoCityScheduling.java ├── 1041. RobotBoundedInCircle.java ├── 1050. PrimeFactors.java ├── 1051. HeightChecker.java ├── 1053.topKFrequentElements.java ├── 1089. DuplicateZeros.java ├── 1103.Panagram_Check.java ├── 118. PascalsTriangle.java ├── 12.IntegerToRoman.java ├── 1208. GetEqualSubstringsWithinBudget.java ├── 121. BestTimeToBuyAndSell.java ├── 122. BestTimeToBuyAndSell2.java ├── 124.BinaryTreeMaxSumPath.java ├── 1295. Find_Number_with_even.java ├── 1299.ReplaceElementswithGreatestElementonRightSide.java ├── 13.RomanToInteger.java ├── 1310. XOR Queries of a Subarray.java ├── 1315. Sum of Nodes with Even-Valued Grandparent.java ├── 1346. CheckIfNandItsDoubleExist.java ├── 1395. Count number of teams.java ├── 14. longestCommonPrefix.java ├── 142_linkedlist_cycle_2.java ├── 1480.RunningSumof1DArray.java ├── 15.3 Sum.java ├── 151.ReverseWordsInAString.java ├── 1510.StoneGameIV.java ├── 1521.FindAValueOfAMysteriousFunctionClosestToTarget.java ├── 1525.NumberOfGoodWaysToSplitAString.java ├── 187. RepeatedDnaSequences.java ├── 19. RemoveNthNodeFromEndOfList.java ├── 198. HouseRobber.java ├── 2.Add Two Numbers.java ├── 20. ValidParentheses.java ├── 201. Bitwise AND of Numbers Range.java ├── 215.KthElementInAnArray.java ├── 22. generatePara.java ├── 224.BasicCalculator.java ├── 229. MajorityElementII.java ├── 23. MergeKSortedLists.java ├── 26. RemoveDuplicatesfromSortedArray.java ├── 27. RemoveElement.java ├── 283. MoveZeroes.java ├── 287. FindTheDuplicateNumber.java ├── 307. Range Sum Query - Mutable.java ├── 322. CoinChange.java ├── 344. ReverseString.java ├── 35.SearchInsertPosition.java ├── 387.First Unique Character in a String.java ├── 4.MedianOfTwoSortedArrays.java ├── 41. First Missing Positive.java ├── 414.ThirdMaximumNumber.java ├── 42. TrappingRainWater.java ├── 421.MaximumXORofTwoNumbersInAnArray.java ├── 438. FindAllAnagramsInAString.java ├── 442. FindAllDuplicatesInAnArray.java ├── 454.4SumII.java ├── 477. Total Hamming Distance.java ├── 48. RotateImage.java ├── 485. Max_Consecutive_ones.java ├── 5.LongestPalindromicSubstring.java ├── 50. Pow(x, n).java ├── 516. Longest Palindromic Subsequence.java ├── 540. SingleElementInASortedArray.java ├── 541. ReverseString2.java ├── 560. Subarray Sum Equals K.java ├── 572. SubtreeOfAnotherTree.java ├── 62. UniquePath.java ├── 621. Task Scheduler.java ├── 647. Palindromic Substrings.java ├── 724. FindPivotIndex.java ├── 749. ContainVirus.java ├── 75.SortColors.java ├── 763. Partition Label.java ├── 78. Subsets.java ├── 784.LetterCasePermutation.java ├── 79. WordSearch.java ├── 797. AllPathsFromSourceToTarget.java ├── 829. ConsecutiveNumberSum.java ├── 84. LargestRectangleInHistogram.java ├── 88. MergeSortedArrays.java ├── 930. Binary Subarrays With Sum.java ├── 941. ValidMountainArray.java ├── 983. MinimumCostForTickets.java └── Top_K_Frequent_Elements.java ├── LICENSE ├── Python ├── 1.TwoSum.py ├── 1007. MinimumDominoRotationsForEqualRow.py ├── 1013. PartitionArrayIntoThreePartsWithEqualSum.py ├── 1119. RemoveVowelFromString.py ├── 1143. LongestCommonSubsequence.py ├── 118. PascalsTriangle.py ├── 1189. MaximumNumberOfBalloons.py ├── 12. Integer to Roman.py ├── 122.BestTimeToBuyAndSellStock-II.py ├── 1221. SplitAStringInBalancedStrings.py ├── 1232.CheckIfItIsAStraightLine.py ├── 1277. CountSquareSubmatricesWithAllOnes.py ├── 1289.MatrixSpiral.py ├── 13. RomanToInteger.py ├── 1342. NumberOfSteps.py ├── 1351. CountNegativeNumbersInASortedMatrix.py ├── 1356.SortIntegersByNumberof1Bits.py ├── 136.SingleNumber.py ├── 137. SingleNumberII.py ├── 138. CopyListWithRandomPointer.py ├── 1390. FourDivisors.py ├── 14. LongestCommonPrefix.py ├── 1436. DestinationCity.py ├── 1450. NumberOfStudentsDoingHomeworkAtAGivenTime.py ├── 1470. ShuffleTheArray.py ├── 148. SortList.py ├── 1480. RunningSumof1DArray.py ├── 15. 3sum.py ├── 1502.CanMakeArithmeticProgressionFromSequence.py ├── 1588. SumofAllOddLengthSubarrays.py ├── 16. 3SumClosest.py ├── 162.FindPeakElement.py ├── 169.MajorityNumber.py ├── 17. LetterCombinationsOfAPhoneNumber.py ├── 172. FactorialTrailingZeroes.py ├── 19. Remove Nth Node From End of List.py ├── 198. House Robber.py ├── 2. AddTwoNumbers.py ├── 20. ValidParentheses.py ├── 200. Number of Islands.py ├── 204. CountPrimes.py ├── 205.IsomorphicStrings.py ├── 208. ImplementTrie.py ├── 21. Merge Two Sorted Lists.py ├── 21. MergeTwoSortedLists.py ├── 215.KthLargestElementInAnArray.py ├── 217.ContainsDuplicate.py ├── 221. MaximalSquare.py ├── 224. BasicCalculator.py ├── 225.ImplementStackUsingQueues.py ├── 226. InvertBinaryTree.py ├── 227. BasicCalculatorII.py ├── 23. MergeKSortedList.py ├── 230.KthSmallestElementinaBST.py ├── 239. Sliding Window Maximum.py ├── 24. Swap Nodes in Pairs.py ├── 25. ReverseNodesInK-Group.py ├── 26. Remove Duplicates from Sorted Array.py ├── 263.UglyNumbers.py ├── 27. RemoveElement.py ├── 28. Implement strStr().py ├── 287. FindTheDuplicateNumber.py ├── 295. FindMedianFromDataStream.py ├── 3. LongestSubstringWithoutRepeatingCharacters.py ├── 33. Search in Rotated Sorted Array.py ├── 338. CountingBits.py ├── 344. ReverseString.py ├── 347. TopKFrequentElements.py ├── 35. SearchInsertPosition.py ├── 367.ValidPerfectSquare.py ├── 368. LargestDivisibleSubset.py ├── 37. SudokuSolver.py ├── 387.FirstUniqueCharInString.py ├── 39. combinationSum.py ├── 4. MedianOfTwoSortedArrays.py ├── 41. FirstMissingPositive.py ├── 41. firstMissingPositive.py ├── 416. PartitionEqualSubsetSum.py ├── 42.TrappingRainWater.py ├── 43. MultiplyStrings.py ├── 44. WildcardMatching.py ├── 441. ArrangingCoins.py ├── 448.FindAllNumbersDisappearedinanArray.py ├── 455. AssignCookies.py ├── 461.HammingDistance.py ├── 485. MaxConsecutiveOnes.py ├── 49. GroupAnagrams.py ├── 5.LongestPalindromicSubstring.py ├── 500.KeyboardRow.py ├── 504. Base7.py ├── 51. N-Queens.py ├── 559. MaximumDepthOfN-aryTree.py ├── 572. SubtreeOfAnotherTree.py ├── 58. length_of_last_word.py ├── 636. ExclusiveTimeOfFunctions.py ├── 64. MinPathSum.py ├── 647. PalandromicSubstrings.py ├── 66. PlusOne.py ├── 7.ReverseInteger.py ├── 704. BinarySearch.py ├── 728. SelfDividingNumbers.py ├── 73. SetMatrixZeroes.py ├── 766. ToeplitzMatrix.py ├── 767. ReorganizeString.py ├── 771. Jewels and Stone.py ├── 785. IsGraphBipartite.py ├── 8.PalindromeChecker.py ├── 838. Push Dominoes.py ├── 84. maximumAreaHistogram.py ├── 88.MergeSortedArray.py ├── 9.Palindrome Number.py ├── 905.SortArrayByParity.py ├── 938. RangeSumofBST.Py ├── 941. ValidMountainArray.py ├── 953. VerifyingAnAlienDictionary.py ├── 977.SquaresOfASortedArray.py ├── 985. Sum of Even Numbers After Queries.py ├── findMinFibonacciNumbers.py └── longestMountatinSubarray..py ├── README.md └── SQL ├── 175. CombineTwoTables.sql ├── 176. SecondHighestSalary.sql ├── 180. ConsectiveNumbers.sql ├── 181. EmployeesEarningMoreThanTheirManagers.sql ├── 182. DuplicateEmails.sql ├── 183. CustomersWhoNeverOrder.sql ├── 196. DeleteDuplicateEmails.sql ├── 595. Big Countries.sql ├── 601. HumanTrafficOfStadium.sql ├── 601. Human_Traffic_of_Stadium.sql ├── 626. ExchangeSeats.sql ├── 627. SwapSalary.sql └── 628. AvgFemSalGreThanMaleSal.sql /.github/ISSUE_TEMPLATE/create-an-issue.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Create an Issue 3 | about: 'Template following Contribution Guidelines ' 4 | title: Problem Number | Title | Language 5 | labels: good first issue 6 | assignees: '' 7 | 8 | --- 9 | 10 | ## **`Title`** - 11 | 12 | **What will change** - 13 | 14 | ### Type of Issue - 15 | 16 | Please add/delete options that are not relevant. 17 | 18 | - [x] Adding New Code 19 | - [x] Improving Code 20 | - [x] Improving Documentation 21 | - [x] Bug Fix 22 | 23 | ### Programming Language 24 | 25 | Please add/delete options that are not relevant. 26 | 27 | - [x] Python 28 | - [x] C++ 29 | - [x] Java 30 | - [x] SQL 31 | 32 | ### Self Check 33 | 34 | - Ask for issue assignment and wait to get assigned to it before making Pull Request. 35 | - Add your file in the proper folder 36 | - `Clean Code` and `Documentation` for better readability 37 | - Add `Title` and `Description` of the program in the file 38 | 39 | :star2: Star it :fork_and_knife:Fork it :handshake: Contribute to it! 40 | 41 | Discord server ✉️ - https://discord.gg/CXksGdn 42 | 43 | Happy Coding, 44 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ## Pull Request Template 2 | 3 | ### What have you Changed(must) 4 | 5 | Write here what you have changed in the codebase 6 | 7 | ### Issue no.(must) - # 8 | 9 | Pr will be close and marked as spam. If issue number not found or issue was assigned to someone else. 10 | Marking as spam can block your account from HacktoberFest. 11 | ### Self Check(Tick After Making pull Request) 12 | 13 | - [ ] This issue was assigned to me if not it will be marked as spam. 14 | - [ ] My file is in the proper folder 15 | - [ ] I am following clean code and Documentation. 16 | - [ ] I have added the title and what program will do first in the file 17 | - [ ] I have named the file as (Problem #). (Problem Title(in Camel Case)).(extension) 18 | ex. 2. AddToNumbers.py 19 | 20 | ### README - [How to Contribute](https://github.com/SSKale1/LeetCode-Solutions/blob/master/CONTRIBUTING.md) 21 | -------------------------------------------------------------------------------- /C++/1015. Smallest Integer Divisible by K.cpp: -------------------------------------------------------------------------------- 1 | // problem - 1015. Smallest Integer Divisible by K 2 | 3 | /* 4 | Given a positive integer K, you need to find the length of the smallest positive integer N 5 | such that N is divisible by K, and N only contains the digit 1. 6 | 7 | Return the length of N. If there is no such N, return -1. 8 | 9 | Note: N may not fit in a 64-bit signed integer. 10 | */ 11 | 12 | class Solution { 13 | public: 14 | int smallestRepunitDivByK(int K) { 15 | // if either k is even(divisible by 2) or divisible by 5 16 | if(!(K&1) || !(K%5)) return -1; 17 | 18 | int rem = 0; 19 | for(int i=1; i<=K; i++) { 20 | rem = (rem * 10 + 1) % K; 21 | 22 | if(rem == 0) return i; 23 | } 24 | 25 | return -1; 26 | } 27 | }; 28 | 29 | // Time Complexity = O(K) 30 | // Space Complexity = O(1) -------------------------------------------------------------------------------- /C++/1025. DivisorGame.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem 1025 - Divisor Game 3 | 4 | Alice and Bob take turns playing a game, with Alice starting first. 5 | Initially, there is a number N on the chalkboard. On each player's turn, that player makes a move consisting of: 6 | - Choosing any x with 0 < x < N and N % x == 0. 7 | - Replacing the number N on the chalkboard with N - x. 8 | Also, if a player cannot make a move, they lose the game. 9 | Return True if and only if Alice wins the game, assuming both players play optimally. 10 | */ 11 | 12 | class Solution { 13 | public: 14 | bool divisorGame(int N) { 15 | if(N % 2 == 0) return true; //if Alice receives an even number: Bob will always receive an odd number and will lose the game 16 | else return false; //if Alice receives an odd number: Bob will always receive an even number and will win the game 17 | } 18 | }; -------------------------------------------------------------------------------- /C++/104. MaximumDepthOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /*Leetcode Problem #104- Maximum Depth of Binary tree*/ 2 | 3 | /*Finding the height/depth of a binary tree or simply calculating the number of generations/levels from the root node to the leaf nodes.*/ 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * struct TreeNode { 8 | * int val; 9 | * TreeNode *left; 10 | * TreeNode *right; 11 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 12 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 13 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | int maxDepth(TreeNode* root) { 19 | 20 | if(root==NULL){ 21 | return 0; 22 | } 23 | int l = maxDepth(root->left); 24 | int r = maxDepth(root->right); 25 | 26 | return max(l,r)+1; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /C++/1051. HeightChecker.cpp: -------------------------------------------------------------------------------- 1 | //Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height. 2 | //Make a copy of the array, sort the copy and comapre it with the actual array 3 | 4 | class Solution { 5 | public: 6 | int heightChecker(vector& heights) { 7 | vectorarr; 8 | int count=0; 9 | int n=heights.size(); 10 | arr.assign(heights.begin(),heights.end()); 11 | sort(heights.begin(),heights.end()); 12 | for(int i=0;i 0) 20 | { 21 | temp = n_temp % 10; // its give the modulus of the number 22 | solution += temp * temp * temp; // to gets its cube to further calculation 23 | n_temp = n_temp / 10; 24 | } 25 | 26 | if (solution == n) 27 | { 28 | return true; 29 | } 30 | 31 | else 32 | { 33 | return false; 34 | } 35 | } 36 | }; -------------------------------------------------------------------------------- /C++/1137. N-th Tribonacci Number.cpp: -------------------------------------------------------------------------------- 1 | // problem - 1137. N-th Tribonacci Number 2 | 3 | /* 4 | The Tribonacci sequence Tn is defined as follows: 5 | T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. 6 | 7 | Given n, return the value of Tn. 8 | */ 9 | 10 | class Solution { 11 | // memoization 12 | vector rec = {0,1,1}; 13 | public: 14 | int tribonacci(int n) { 15 | // base case 16 | if(n < rec.size()) return rec[n]; 17 | // memoizing 18 | rec.push_back(tribonacci(n-1) + tribonacci(n-2) + tribonacci(n-3)); 19 | 20 | // final output 21 | return rec[n]; 22 | } 23 | }; 24 | 25 | // Time Complexity = O(n) 26 | // Space Complexity = O(n) [where n is input to tribonacci()] -------------------------------------------------------------------------------- /C++/118. PascalTriangle.cpp: -------------------------------------------------------------------------------- 1 | // Pascal's Triangle 2 | /* 3 | Approach - If we have the row of Pascal's triangle, we can easily compute the next row by each pair of adjacent values. 4 | Algorithm - Pascal's triangle can be classified as dynamic programming because we construct each row based on the previous row. 5 | First, we generate the overall triangle list, which will store each row as a sublist. Then, we check for the special case of 000, as we would otherwise return [1][1][1]. 6 | If numRows>0numRows > 0numRows>0, then we initialize triangle with [1][1][1] as its first row, and proceed to fill the rows. 7 | */ 8 | 9 | class Solution { 10 | public: 11 | vector> generate(int numRows) { 12 | vector> ret; 13 | ret.reserve( numRows ); 14 | for (int n=0; n row = {1}; // n choose 0 16 | row.reserve( n+1 ); 17 | for (int k=1; k<=n; k++) { 18 | row.push_back( row.back() * (n + 1 - k)/k ); 19 | } 20 | ret.push_back(row); 21 | } 22 | return ret; 23 | } 24 | }; -------------------------------------------------------------------------------- /C++/121. BestTimetoBuyandSellStock.cpp: -------------------------------------------------------------------------------- 1 | // Problem: 2 | // Say you have an array for which the ith element is the price of a given stock on day i. 3 | // If you were only permitted to complete at most one transaction 4 | // (i.e., buy one and sell one share of the stock), 5 | // design an algorithm to find the maximum profit. 6 | // Note that you cannot sell a stock before you buy one. 7 | 8 | // Approach: 9 | // Initialize mn variable to first value. Now, find the running difference between current 10 | // value and mn variable, since that would give us the required maximum profit. 11 | 12 | class Solution { 13 | public: 14 | int maxProfit(vector& prices) { 15 | int n = prices.size(); 16 | if (!n) return 0; 17 | int mn = prices[0], ans = 0; 18 | for (int i = 1; i < n; i++) 19 | { 20 | ans = max({0, ans, prices[i] - mn}); 21 | if (prices[i] < mn) 22 | mn = prices[i]; 23 | } 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/1221. SplitaStringInBalancedStrings.cpp: -------------------------------------------------------------------------------- 1 | //Balanced strings are those who have equal quantity of 'L' and 'R' characters. 2 | //Given a balanced string s split it in the maximum amount of balanced strings. 3 | //Return the maximum amount of splitted balanced strings. 4 | 5 | class Solution { 6 | public: 7 | int balancedStringSplit(string s) { 8 | int count = 0,countSubStr = 0; 9 | for(char c : s){ 10 | if(c == 'R') 11 | count++; 12 | else 13 | count--; 14 | if(count == 0){ 15 | countSubStr++; 16 | count = 0; 17 | } 18 | } 19 | return countSubStr; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/124. Binary_Tree_Maximum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int func(TreeNode* root,int &sum){ 15 | if(root==nullptr){ 16 | return 0; 17 | } 18 | int l=max(0,func(root->left,sum)); 19 | int r=max(0,func(root->right,sum)); 20 | sum=max(sum,root->val+l+r); 21 | return root->val+max(l,r); 22 | } 23 | int maxPathSum(TreeNode* root) { 24 | int sum=INT_MIN; 25 | func(root,sum); 26 | return sum; 27 | 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /C++/125. ValidPalindrome.cpp: -------------------------------------------------------------------------------- 1 | // First of all, made a string p using string s with all tha characters which can be a part of the palindrome, which means, considering only alphanumeric characters and ignoring cases. 2 | // Then using while loop, traversed string p from both sides (from the beginning as well as the end) to check if it forms a palindrome. 3 | 4 | bool isPalindrome(string s) { 5 | string p; 6 | for(int i=0;i> shiftGrid(vector>& grid, int k) { 4 | int row = grid.size(); 5 | int col = grid[0].size(); 6 | 7 | //creating a result vector of row * col dimensions 8 | vector> shifted(row, vector(col, 0)); 9 | 10 | //iterating from 0 to (row*col)-1 to store the elements into result matrix 11 | for(int i=0; i [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0] 14 | Time from [1,1] to [3,4] = 3 seconds 15 | Time from [3,4] to [-1,0] = 4 seconds 16 | Total time = 7 seconds 17 | */ 18 | 19 | class Solution { 20 | public: 21 | int minTimeToVisitAllPoints(vector>& points) { 22 | int time=0; 23 | for(int i=0;i v; 20 | while(head!=NULL){ 21 | v.push_back(head->val); 22 | head=head->next; 23 | } 24 | int ans=0,n=v.size(),t=n; 25 | for(int i=0;i m = {{'I', 1}, {'V', 5},{'X', 10},{'L', 50}, 11 | {'C', 100},{'D', 500},{'M', 1000}}; 12 | 13 | int total = 0; 14 | for(int i = 0; i < s.length(); i++){ 15 | 16 | //1.The letters are arranged from left to right 17 | in descending order of value to form a number 18 | 19 | if(m[s[i+1]] <= m[s[i]]) total += m[s[i]]; 20 | 21 | //2.when you see a lower value in front of a 22 | higher value (subtract) 23 | else total -= m[s[i]]; 24 | } 25 | return total; 26 | } 27 | -------------------------------------------------------------------------------- /C++/1313. Decompress Run-Length Encoded List.cpp: -------------------------------------------------------------------------------- 1 | 2 | /** This is cake-walk problem, with simple bruteforce approach. 3 | * Here we were given a value and its frequency and we have to make a new vector so that each value is repeated 4 | * equivalent to its frequency times. 5 | * So in the input even indices represents frquency and odd indices represents particular value. (Zero based indexing) 6 | * So simply walk through the even indices and get the adjacent value and put that value in the new vector for desired number of times. 7 | */ 8 | 9 | class Solution { 10 | public: 11 | vector decompressRLElist(vector &nums) { 12 | vector ans; 13 | for (int i = 0; i < nums.size(); i += 2) { //loop through even indices 14 | int frequency = nums[i]; //Get the frequency 15 | int value = nums[i + 1]; //Get the particular value 16 | for (int j = 0; j < frequency; ++j) { // Add that value to new vector for frquency times 17 | ans.push_back(value); 18 | } 19 | } 20 | return ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /C++/134. GasStation.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. 4 | You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). 5 | You begin the journey with an empty tank at one of the gas stations. 6 | Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. 7 | */ 8 | 9 | class Solution { 10 | public: 11 | int canCompleteCircuit(vector& gas, vector& cost) { 12 | int sumGas = 0; 13 | int sumCost = 0; 14 | int start = 0; 15 | int tank = 0; 16 | for(int i = 0;i=sumCost) return start; 25 | else return -1; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /C++/1342. NumberofStepstoReduceaNumbertoZero.cpp: -------------------------------------------------------------------------------- 1 | //Given a non-negative integer num, return the number of steps to reduce it to zero. 2 | //If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. 3 | 4 | class Solution { 5 | public: 6 | int numberOfSteps (int num) { 7 | int counter = 0; 8 | while(num) 9 | { 10 | if(num%2==0) 11 | { 12 | num = num/2; 13 | } 14 | else 15 | { 16 | num = num-1; 17 | } 18 | counter++; 19 | } 20 | return counter; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /C++/1356.SortIntegersByTheNumberOf1Bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | //counting the no. of 1's in the binary representation of each integer in the array 4 | static int countBits(int n) 5 | { 6 | int count=0; 7 | while(n>0) 8 | { 9 | //returns the no. of 1's in binary form 10 | n = n&(n-1); 11 | count++; 12 | } 13 | return count; 14 | } 15 | //checking the no. of 1-bits in the successive numbers of the array for sorting them 16 | static bool cmp(int a, int b) 17 | { 18 | if(countBits(a)==countBits(b)) 19 | { 20 | return acountBits(b)) 24 | { 25 | return false; 26 | } 27 | return true; 28 | } 29 | vector sortByBits(vector& arr) { 30 | //sorting the array on the basis of frequency of no. of 1's in ascending order 31 | sort(begin(arr), end(arr),cmp); 32 | return arr; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /C++/1431. KidsWithTheGreatesNumberOfCandies.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Solution to Kids With the Greatest Number of Candies in CPP 3 | * 4 | * author: ITES7321 5 | * ref:https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ 6 | */ 7 | 8 | class Solution { 9 | public: 10 | vector kidsWithCandies(vector& candies, int extraCandies) { 11 | int m = *max_element(candies.begin(),candies.end()); 12 | vector v(candies.size()); 13 | for(int i=0;i= m) 16 | v[i] = true; 17 | } 18 | return v; 19 | } 20 | }; -------------------------------------------------------------------------------- /C++/145.BinaryTreePostorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /* Algorithm Postorder(tree) 2 | * 1. Traverse the left subtree, i.e., call postorderTraversal(left-subtree) 3 | * 2. Traverse the right subtree, i.e., call postorderTraversal(right-subtree) 4 | * 3. Visit the root. 5 | * 6 | * While visiting the root, I'm pushing the value at that node and returning the final vector as output. 7 | */ 8 | 9 | class Solution { 10 | public: 11 | vector v; 12 | vector postorderTraversal(TreeNode* root) { 13 | //base condition 14 | if(root==NULL) 15 | return v; 16 | 17 | postorderTraversal(root->left); 18 | postorderTraversal(root->right); 19 | v.push_back(root->val); 20 | 21 | return v; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /C++/1470. ShuffleTheArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 1470. Shuffle the array 3 | 4 | Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. 5 | 6 | Return the array in the form [x1,y1,x2,y2,...,xn,yn]. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: nums = [2,5,1,3,4,7], n = 3 13 | Output: [2,3,5,4,1,7] 14 | Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]. 15 | Example 2: 16 | 17 | Input: nums = [1,2,3,4,4,3,2,1], n = 4 18 | Output: [1,4,2,3,3,2,4,1] 19 | Example 3: 20 | 21 | Input: nums = [1,1,2,2], n = 2 22 | Output: [1,2,1,2] 23 | 24 | 25 | Constraints: 26 | 27 | 1 <= n <= 500 28 | nums.length == 2n 29 | 1 <= nums[i] <= 10^3 30 | 31 | Link: https://leetcode.com/problems/shuffle-the-array/ 32 | 33 | */ 34 | 35 | 36 | class Solution { 37 | public: 38 | vector shuffle(vector& nums, int n) { 39 | vector answer; 40 | for(int i = 0; i runningSum(vector& nums) { 4 | vector b; 5 | long int sum = 0; 6 | for(int i=0;i& salary) { 4 | int n=salary.size(); 5 | 6 | //changed long double -> double! 7 | double sum=0.0; 8 | 9 | //sorting the salary array in increasing order 10 | sort(begin(salary), end(salary)); 11 | 12 | //iterating from 2nd element till 2nd last element to store their sum 13 | for(int i=1; i<=n-2; i++) 14 | { 15 | sum = sum + salary[i]; 16 | } 17 | 18 | //dividing the sum by (n-2) to find the average because we did not include the min(1st) and the 19 | //max(last) element in the salary array, so total employees = n-2 20 | double avg = sum/(n-2); 21 | 22 | return avg; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /C++/1496.PathCrossing.cpp: -------------------------------------------------------------------------------- 1 | /*Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path. */ 2 | 3 | /*Return True if the path crosses itself at any point, that is, if at any time you are on a location you've previously visited. Return False otherwise.*/ 4 | class Solution { 5 | public: 6 | bool isPathCrossing(string path) { 7 | map m; 8 | int x = 0, y = 0; 9 | m["00"]+=1; 10 | for(int i = 0; i < path.size(); i++){ 11 | string temp = ""; 12 | if(path[i]=='N') y+=1; 13 | else if(path[i]=='S') y-=1; 14 | else if(path[i]=='E') x+=1; 15 | else if(path[i]=='W') x-=1; 16 | temp = to_string(x); 17 | temp +=to_string(y); 18 | m[temp]+=1; 19 | if(m[temp] > 1) return true; 20 | } 21 | return false; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /C++/1502.CanMakeArithmeticProgressionFromSequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canMakeArithmeticProgression(vector& arr) { 4 | int n = arr.size(); 5 | 6 | //since, there is no 3rd element to compare 7 | if(n==2) 8 | return true; 9 | sort(begin(arr), end(arr)); 10 | for(int i=0; i j) 26 | result = s.substr(j,i-j) + " " + result; 27 | j = i+1; 28 | } 29 | else if(i == s.size()-1) 30 | result = s.substr(j,s.size()-j) + " " + result; 31 | } 32 | s=result.substr(0,result.size()-1); 33 | return s; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /C++/1512. NumberofGoodPairs.cpp: -------------------------------------------------------------------------------- 1 | //Given an array of integers nums. 2 | //A pair (i,j) is called good if nums[i] == nums[j] and i < j. 3 | //Return the number of good pairs. 4 | 5 | class Solution { 6 | public: 7 | int numIdenticalPairs(vector& nums) { 8 | int answer = 0; 9 | map freq; 10 | for(int n : nums) { 11 | freq[n]++; 12 | if(freq[n] >= 2) 13 | answer+= freq[n] - 1; 14 | } 15 | return answer; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/1528. Shuffle String.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s and an integer array indices of the same length. 3 | The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string. 4 | Return the shuffled string. 5 | 6 | Example 1: 7 | 8 | Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3] 9 | Output: "leetcode" 10 | Explanation: As shown, "codeleet" becomes "leetcode" after shuffling. 11 | 12 | Example 2: 13 | 14 | Input: s = "abc", indices = [0,1,2] 15 | Output: "abc" 16 | Explanation: After shuffling, each character remains in its position. 17 | 18 | Example 3: 19 | 20 | Input: s = "aiohn", indices = [3,1,4,2,0] 21 | Output: "nihao" 22 | 23 | Example 4: 24 | 25 | Input: s = "aaiougrt", indices = [4,0,2,6,7,3,1,5] 26 | Output: "arigatou" 27 | */ 28 | 29 | class Solution { 30 | public: 31 | string restoreString(string s, vector& indices) { 32 | string s1=s; 33 | int j=0; 34 | for(auto i:indices) 35 | { 36 | s1[i]=s[j++]; 37 | } 38 | return s1; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /C++/153.FindMinimuminRotatedSortedArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& nums) { 4 | int n = nums.size(); 5 | //maintaining relevant pointers for binary search 6 | int left = 0; 7 | int right = n-1; 8 | int mid; 9 | 10 | //edge case 11 | if(n==1) 12 | return nums[0]; 13 | 14 | while(left nums[right]) 20 | left = mid+1; 21 | //either left side was rotated or is sequential, implying that the min. value can be found between [left, mid] 22 | else 23 | right = mid; 24 | } 25 | //the value at nums[left] will have the min. value 26 | return nums[left]; 27 | } 28 | }; 29 | 30 | //TC: O(logn), for binary search 31 | //SC: O(1), for constant space 32 | -------------------------------------------------------------------------------- /C++/1539. KthMissingPositiveNumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement: 3 | Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. 4 | Find the kth positive integer that is missing from this array. 5 | Constraints: 6 | 1 <= arr.length <= 1000 7 | 1 <= arr[i] <= 1000 8 | 1 <= k <= 1000 9 | arr[i] < arr[j] for 1 <= i < j <= arr.length 10 | Approach: 11 | Let's assume that no element is present in the array. In this case, answer should be equal to k. 12 | Now we traverse through the array in linear time. 13 | For every element we encounter having its value greater than answer, we increment our answer by one 14 | */ 15 | 16 | //Solution: 17 | 18 | class Solution { 19 | public: 20 | int findKthPositive(vector& arr, int k) { 21 | int ans = k; 22 | for(int i = 0; i < arr.size(); i++){ 23 | if(arr[i] <= ans) 24 | ans++; 25 | } 26 | return ans; 27 | } 28 | }; 29 | 30 | -------------------------------------------------------------------------------- /C++/154. FindMinimumInRotatedSortedArrayII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 154. Find Minimum in Rotated Sorted Array II 3 | 4 | Many people think we need to do binary search or magic. But the best solution is to simply just 5 | search trough the array in O(n) time. 6 | 7 | Read this discussion: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/discuss/48849/Stop-wasting-your-time.-It-most-likely-has-to-be-O(n). 8 | */ 9 | 10 | class Solution { 11 | public: 12 | int findMin(vector& nums) { 13 | int smol = nums[0]; 14 | for (int i = 0; i < nums.size(); i++) { 15 | if (nums[i] < smol) { 16 | smol = nums[i]; 17 | } 18 | } 19 | return smol; 20 | } 21 | }; -------------------------------------------------------------------------------- /C++/1557.MinimumNumberOfVerticesToReachAllNodes.cpp: -------------------------------------------------------------------------------- 1 | /* Given a graph, we need to find the smallest set of vertices from which all nodes in the graph are reachable . 2 | So, we will mark all the nodes that are reachable from any other node as true and in the last, we will check which nodes have their in-degree as 0. 3 | The nodes with 0 in-degree would be our answer. 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | vector findSmallestSetOfVertices(int n, vector>& edges) { 10 | bool visited[n]; 11 | for(int i = 0; i < n; i++){ 12 | visited[i] = false; 13 | } 14 | /* All the nodes that are reachable from any other node will be marked as true */ 15 | for(vector i : edges){ 16 | visited[i[1]] = true; 17 | } 18 | /* Nodes with in-degree 0 would be added to the ans vector */ 19 | vectorans; 20 | for(int i = 0; i < n; i++){ 21 | if(visited[i] == false){ 22 | ans.push_back(i); 23 | } 24 | } 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /C++/1572. Matrix Diagonal Sum.cpp: -------------------------------------------------------------------------------- 1 | /*Given a square matrix mat, return the sum of the matrix diagonals. 2 | 3 | Only include the sum of all the elements on the primary diagonal(digonal from top-left corner to bottom-right corner) and 4 | all the elements on the secondary diagonal(top-right corner to bottom-left corner) that are not part of the primary diagonal.*/ 5 | 6 | class Solution { 7 | public: 8 | int diagonalSum(vector>& mat) { 9 | int n=mat.size(); 10 | int left=0,right=n-1,sum=0; 11 | for(int i=0;i& arr) { 21 | long long sum=0; 22 | int n= arr.size(); 23 | for(int win = 1; win<=n ; win+=2){ 24 | for(int i=0; i < n-win+1; i++){ 25 | for(int j=i; j &nums) { 10 | int x = 0; 11 | while (true) { 12 | if (x > 1000) break; // As all the values are in range [0,1000] 13 | int count = 0; 14 | for (int i = 0; i < nums.size(); ++i) { //Count the number of values greater than x 15 | if (nums[i] >= x) ++count; 16 | } 17 | if (count == x) return x; 18 | ++x; 19 | } 20 | return -1; 21 | } 22 | }; -------------------------------------------------------------------------------- /C++/162.FindPeakElement.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findPeakElement(vector& nums) { 4 | 5 | int l = 0; 6 | int r = nums.size()-1; 7 | int mid; 8 | 9 | //iterating over the entire array using binary search method 10 | while(l& nums) { 11 | int n = nums.size(); 12 | 13 | // to handle edge case 14 | if(n < 2) return 0; 15 | 16 | // sorting the nums array and looping through to get maximum difference 17 | sort(nums.begin(), nums.end()); 18 | int answer = 0; 19 | for(int i=1; i0) 13 | { 14 | //for iterating each index from the end 15 | n--; 16 | //changing the last value from 'a' to 'z' or k, whichever is minimum 17 | result[n] = result[n] + min(25,k); 18 | //decrementing k by the value to which 'a' was changed 19 | k = k - min(25,k); 20 | } 21 | 22 | return result; 23 | } 24 | }; 25 | 26 | /* 27 | You can checkout this link for understanding the problem through an example: 28 | https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/discuss/1871662/JavaC%2B%2B-Easiest-Possible-Exaplained!! 29 | 30 | */ 31 | -------------------------------------------------------------------------------- /C++/167. TwoSumII-InputArrayIsSorted.cpp: -------------------------------------------------------------------------------- 1 | /* PROBLEM: Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. 2 | 3 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. 4 | 5 | APPROACH: impplemented two sum using two pointers strating from start and end of given vector 6 | 7 | */ 8 | 9 | 10 | class Solution { 11 | public: 12 | vector twoSum(vector& numbers, int target) { 13 | vector v; 14 | int l=numbers.size(); 15 | for(int i=0,j=l-1;i=0;){ 16 | if(numbers[i]+numbers[j]==target){ 17 | v.push_back(i+1); 18 | v.push_back(j+1); 19 | return v; 20 | } 21 | else if(numbers[i]+numbers[j]>target) j--; 22 | else i++; 23 | } 24 | return {1}; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/1678.GoalParserInterpretation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string interpret(string command) { 4 | int n = command.size(); 5 | string result=""; 6 | 7 | for(int i=0; i G 31 | () -> o 32 | (al) -> al 33 | 34 | For letter G, just check the ith index. 35 | For () and (al), check if i+1 is equal to either ')' or 'a' 36 | - if i+1 == ')' , append 'o' to the result and increment i by 1 37 | - if i+1 == 'a' , append "al" and increment i by 3, since (al) has 4 characters 38 | */ 39 | -------------------------------------------------------------------------------- /C++/169. MajorityElement.cpp: -------------------------------------------------------------------------------- 1 | // Sorted the array and found out if the count of the element becomes more than n/2, and returned it. 2 | 3 | int majorityElement(vector& nums) { 4 | int j; 5 | sort(nums.begin(),nums.end()); 6 | int c=1; 7 | int n=nums.size(); 8 | for(int i=0;in/2) 14 | { 15 | j=i; 16 | return nums[j]; 17 | } 18 | } 19 | return nums[j]; 20 | } 21 | -------------------------------------------------------------------------------- /C++/1768.MergeStringsAlternately.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string mergeAlternately(string word1, string word2) { 4 | 5 | //pointers for word1 and word2 respectively 6 | int a = 0, b = 0; 7 | int n = word1.size(); 8 | int m = word2.size(); 9 | string result=""; 10 | 11 | //iterating over word1 and word2, thereby pushing characters from each word alternatively 12 | while(a>& points) { 4 | 5 | //setting index as -1 initially 6 | int index=-1; 7 | int distance = INT_MAX; 8 | int manhattanDist; 9 | 10 | for(int i=0; i manhattanDist) 19 | { 20 | distance = manhattanDist; 21 | index = i; 22 | } 23 | } 24 | } 25 | return index; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /C++/179.Largest Number.cpp: -------------------------------------------------------------------------------- 1 | //The logic used here is to sort all the strings using comparator function func to ensure the final concatenation leads to the Largest Number 2 | 3 | class Solution { 4 | public: 5 | static bool func(int x,int y)//This func is used to check among the two strings which is to be front and which has to be at the backend 6 | { 7 | string s1=to_string(x); 8 | string s2=to_string(y); 9 | return s1+s2>s2+s1; 10 | } 11 | string largestNumber(vector& nums) { 12 | sort(nums.begin(),nums.end(),func); 13 | string s=""; 14 | for(int i=0;i0) 7 | { 8 | //1 is the number where only the last bit is 1,(x&1)=1 if the last bit of x is 1 and 0 otherwise 9 | if(n&1 == 1) 10 | count++; 11 | 12 | // shift bits to remove lower bit 13 | n = n >> 1; 14 | return count; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /C++/1929. Concatenation of Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Submitted by vipul kumar singh 3 | concatenation means combining/ joining of two letters , string or etc 4 | question link :: https://leetcode.com/problems/concatenation-of-array/ 5 | */ 6 | class Solution { 7 | public: 8 | vector getConcatenation(vector& nums) { 9 | 10 | int size = nums.size(); // simply to get the length/size of the vector (int type ) 11 | 12 | for (auto i = 0 ; i val:0)+((l2)?l2->val:0)+c; 19 | te->next=new ListNode(s%10); 20 | te=te->next; 21 | 22 | c=s/10; 23 | if(l1) 24 | l1=l1->next; 25 | if(l2) 26 | l2=l2->next; 27 | } 28 | while(c) 29 | { 30 | te->next=new ListNode(c%10); 31 | c=c/10; 32 | te=te->next; 33 | } 34 | return head->next; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /C++/201. BitwiseANDofNumbersRange.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 201. Bitwise AND of Numbers Range 3 | 4 | Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. 5 | 6 | Example 1: 7 | 8 | Input: [5,7] 9 | Output: 4 10 | 11 | */ 12 | 13 | class Solution { 14 | public: 15 | int rangeBitwiseAnd(int m, int n) { 16 | 17 | int count=0; 18 | while(m>1; 20 | n=n>>1; 21 | count++; 22 | } 23 | return n<next; 28 | curr->next=prev; 29 | prev=curr; 30 | curr=temp; 31 | } 32 | return prev; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /C++/21. MergeTwoSortedLists.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | 21. Merge Two Sorted Lists 4 | 5 | https://leetcode.com/problems/merge-two-sorted-lists/ 6 | 7 | Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. 8 | 9 | */ 10 | 11 | 12 | /* 13 | 14 | Solution: 15 | 16 | -> Simple and short recursive code that works by pointer manipulation. 17 | -> Uses O(1) space apart from stack usage of recursive function calls 18 | 19 | */ 20 | 21 | class Solution { 22 | public: 23 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 24 | if(l1 == NULL) return l2; 25 | if(l2 == NULL) return l1; 26 | if(l1 -> val < l2 -> val){ 27 | l1 -> next = mergeTwoLists(l1 -> next, l2); 28 | return l1; 29 | } else{ 30 | l2 -> next = mergeTwoLists(l1, l2 -> next); 31 | return l2; 32 | } 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /C++/2139.MinimumMovesToReachTargetScore.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minMoves(int target, int maxDoubles) { 4 | 5 | //x is the integer =1 from which we will start the game 6 | int x = 1; 7 | int moves = 0; 8 | 9 | //reducing the value of target to reach x, so we need to ensure that target>x and we don't run out 10 | //on maxDoubles 11 | while(target > x && maxDoubles!=0) 12 | { 13 | //decrement by 1 if the target is odd, to make it even 14 | if(target%2==1) 15 | target--; 16 | 17 | //divide by 2 if the target is even, and decrement the maxDoubles 18 | else 19 | { 20 | target = target/2; 21 | maxDoubles--; 22 | } 23 | //incrementing the move variable as one of the above operations took place 24 | moves++; 25 | } 26 | 27 | //target-x is the remaining number of subtractions(-1) which we will add to the moves 28 | moves = moves + (target - x); //or target - 1 29 | return moves; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /C++/217. ContainsDuplicate.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool containsDuplicate(vector& nums) { 4 | int n, i; 5 | n = nums.size()-1; 6 | 7 | /* Commenting out this solution because 8 | its time limit exceeded!! 9 | for(i=1; i<=n; i++) 10 | { 11 | for(j=0; j& nums, int k, int t) { 8 | int i,j; 9 | if(nums.size()==0 || nums.size()==1 || k==10000) 10 | { 11 | return false; 12 | } 13 | for(i=0;i>& matrix) { 19 | int r = matrix.size(); 20 | if(r==0) 21 | return 0; 22 | int c = matrix[0].size(); 23 | int dp[r+1][c+1]; 24 | for(int i=0;i<=r;i++){ 25 | for(int j=0;j<=c;j++){ 26 | dp[i][j]=0; 27 | } 28 | } 29 | int ans=0; 30 | for(int i=1;i<=r;i++){ 31 | for(int j=1;j<=c ;j++) 32 | if(matrix[i-1][j-1]=='1'){ 33 | dp[i][j] = 1 + min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1])); 34 | if(ansval>=p->val && root->val <=q->val) || 17 | (root->val<=p->val && root->val >=q->val)) 18 | return root; 19 | if(root->val>p->val && root->val >q->val) 20 | return lowestCommonAncestor(root->left,p,q); 21 | else 22 | return lowestCommonAncestor(root->right,p,q); 23 | 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /C++/24. Swap_Nodes_In_Pairs.cpp: -------------------------------------------------------------------------------- 1 | //24. Swap Nodes in Pairs 2 | //Given a linked list, swap every two adjacent nodes and return its head. 3 | 4 | //You may not modify the values in the list's nodes. Only nodes itself may be changed. 5 | 6 | /* For example: 7 | Input: head = [1,2,3,4] 8 | Output: [2,1,4,3] 9 | */ 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * struct ListNode { 14 | * int val; 15 | * ListNode *next; 16 | * ListNode() : val(0), next(nullptr) {} 17 | * ListNode(int x) : val(x), next(nullptr) {} 18 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 19 | * }; 20 | */ 21 | class Solution { 22 | public: 23 | ListNode* swapPairs(ListNode* head) { 24 | if(head == NULL || head->next == NULL) { 25 | return head; 26 | } 27 | 28 | ListNode* newhead = head->next; 29 | ListNode* temp = newhead->next; 30 | newhead->next = head; 31 | head->next = swapPairs(temp); 32 | return newhead; 33 | } 34 | }; -------------------------------------------------------------------------------- /C++/240.SearchA2DMatrixII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool searchMatrix(vector>& matrix, int target) { 4 | 5 | int row = matrix.size(); 6 | int col = matrix[0].size(); 7 | 8 | //matrix index values from which we start traversing, in this case, top-right corner 9 | int r = 0; 10 | int c = col-1; 11 | 12 | //starting from top-right corner in the matrix and traversing till we reach the boundary 13 | while(r=0) 14 | { 15 | if(target==matrix[r][c]) 16 | return true; 17 | 18 | //rejecting the entire COLUMN if target is less than the current matrix value 19 | else if(target < matrix[r][c]) 20 | c--; 21 | //rejecting the entire ROW if the target is more than the current matrix value 22 | else 23 | r++; 24 | } 25 | return false; 26 | } 27 | }; 28 | 29 | /* 30 | TC: O(row+col), the path traversed from top-right cornet to target 31 | SC: O(1) 32 | */ 33 | -------------------------------------------------------------------------------- /C++/268. MissingNumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 268. Missing Number 3 | 4 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 5 | 6 | Example 1: 7 | 8 | Input: [3,0,1] 9 | Output: 2 10 | Example 2: 11 | 12 | Input: [9,6,4,2,3,5,7,0,1] 13 | Output: 8 14 | */ 15 | 16 | class Solution { 17 | public: 18 | int missingNumber(vector& nums) { 19 | 20 | int len = nums.size(); 21 | int total = (len)*(len+1)/2; 22 | for(int i=0;i& nums, int val) { 7 | int n=nums.size(); 8 | int a=0; 9 | vector v; 10 | for(int i=0;ist; 9 | st.push(-1); 10 | int l=s.length(); 11 | int ans=0; 12 | for(int i=0;i countBits(int num) { 14 | vector dp(num + 1); 15 | dp[0] = 0; 16 | 17 | for(int i = 1; i <= num; i++){ 18 | dp[i] = dp[i >> 1] + (i & 1); 19 | } 20 | 21 | return dp; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /C++/344.ReverseString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void reverseString(vector& s) { 4 | //1st pointer pointing to the start of the string 5 | int a = 0; 6 | //2nd pointer poiting to the end of the string 7 | int b = s.size()-1; 8 | 9 | //iterate over the string till a<=b 10 | while(a<=b) 11 | { 12 | //swap the 2 index values of the string 13 | swap(s[a], s[b]); 14 | a++; 15 | b--; 16 | } 17 | } 18 | }; 19 | 20 | //TC: O(1), SC=O(1) 21 | -------------------------------------------------------------------------------- /C++/347. TopKFrequentElements.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* PROBLEM : Given a non-empty array of integers, return the k most frequent elements. 3 | 4 | APPROACH: Approached using a map data structure to count the frequency of each element. 5 | */ 6 | 7 | 8 | 9 | 10 | class Solution { 11 | public: 12 | vector topKFrequent(vector& nums, int k) { 13 | map m; 14 | for(auto x:nums) m[x]++; 15 | vector> v; 16 | for(auto x:m){ 17 | v.push_back({x.second,x.first}); 18 | } 19 | sort(v.begin(),v.end()); 20 | vector ans; 21 | int ct=0,pt=v.size()-1; 22 | while(ct& nums, int target) { 10 | 11 | int ans; 12 | for(int i=0; itarget){/*at function Returns a reference to the element at that position in the vector*/ 14 | ans = i; 15 | break; 16 | } 17 | } 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /C++/38. CountAndSay.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The count-and-say sequence is the sequence of integers beginning as follows: 3 | 1, 11, 21, 1211, 111221, ... 4 | 1 is read off as one 1 or 11. 5 | 11 is read off as two 1s or 21. 6 | 21 is read off as one 2, then one 1 or 1211. 7 | Given an integer n, generate the nth sequence. 8 | Note: The sequence of integers will be represented as a string. 9 | Example: 10 | if n = 2, 11 | the sequence is 11. 12 | */ 13 | 14 | string Solution::countAndSay(int A) { 15 | string result = ""; 16 | 17 | if(!A) 18 | return result; 19 | 20 | string str = "1"; 21 | int cnt = 1; 22 | 23 | for (int i = 1; i &A) { 21 | long long result = 0; 22 | long long greaterRes = 0; 23 | for (int i = 0; i < A.size(); i++) { 24 | result = 0; 25 | for (int j = 1; j < A.size(); j++) { 26 | result += A[(j+i)%A.size()]; 27 | } 28 | greaterRes = max(result, greaterRes); 29 | } 30 | 31 | return greaterRes; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /C++/414.PartitionEqualSubsetSum.cpp: -------------------------------------------------------------------------------- 1 | //Given a non-empty array containing only positive integers, 2 | //find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. 3 | //This program checks whether it has qual sum or not 4 | class Solution { 5 | public: 6 | int dp[202][20000]; 7 | bool check(vector& nums,int sum,int n) 8 | { 9 | if(n==0)return false; 10 | if(sum==0)return true; 11 | if(dp[n][sum]!=-1)return dp[n][sum]; 12 | if(sum>=nums[n-1]) 13 | return dp[n][sum]=check(nums,sum-nums[n-1],n-1)|| check(nums,sum,n-1); 14 | else 15 | return dp[n][sum]=check(nums,sum,n-1); 16 | } 17 | bool canPartition(vector& nums) { 18 | int n=nums.size(); 19 | memset(dp,-1,sizeof(dp)); 20 | int sum=0; 21 | for(int i=0;i& height) { 12 | // detect edge case 13 | if (height.size() < 2) return 0; 14 | 15 | int n = height.size(); 16 | int left_max[n]; 17 | int right_max[n]; 18 | 19 | left_max[0] = height[0]; 20 | for (int i = 1; i < n; i ++) { 21 | left_max[i] = max(left_max[i-1], height[i]); 22 | } 23 | right_max[n-1] = height[n-1]; 24 | for (int i = n-2; i >= 0 ; i --) { 25 | right_max[i] = max(right_max[i+1], height[i]); 26 | } 27 | 28 | int ans = 0; 29 | for (int i = 0; i < n; i ++) { 30 | ans += min(left_max[i], right_max[i]) - height[i]; 31 | } 32 | 33 | return ans; 34 | } 35 | }; -------------------------------------------------------------------------------- /C++/448. Find_All_Numbers_Disappeared_in_an_Array.cpp: -------------------------------------------------------------------------------- 1 | //Assigned #1016 2 | //CODE 3 | 4 | class Solution { 5 | public: 6 | vector findDisappearedNumbers(vector& nums) { 7 | set> s; 8 | vector v;//return result vector 9 | for(int i=0;i freq[b] || freq[a] == freq[b] && a < b; 28 | }); 29 | 30 | return s; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /C++/461. HammingDistance.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 461. Hamming Distance 3 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 4 | 5 | Given two integers x and y, calculate the Hamming distance. 6 | 7 | Note: 8 | 0 ≤ x, y < 231. 9 | 10 | Example: 11 | 12 | Input: x = 1, y = 4 13 | 14 | Output: 2 15 | 16 | Explanation: 17 | 1 (0 0 0 1) 18 | 4 (0 1 0 0) 19 | ↑ ↑ 20 | 21 | The above arrows point to positions where the corresponding bits are different. 22 | */ 23 | 24 | class Solution { 25 | 26 | int check(int n) { 27 | int count=0; 28 | while(n) { 29 | count = count+(n&1); 30 | n=n>>1; 31 | } 32 | return count; 33 | } 34 | 35 | public: 36 | int hammingDistance(int x, int y) { 37 | return check(x^y); 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /C++/476. NumberComplement.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 476. Number Complement 3 | 4 | Given a positive integer num, output its complement number. The complement strategy is to flip the bits of its binary representation. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: num = 5 11 | Output: 2 12 | Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. 13 | 14 | */ 15 | 16 | class Solution { 17 | public: 18 | int findComplement(int n) { 19 | // Calculate number of bits of N-1; 20 | int x = log2(n) ; 21 | int m = 1 << x; 22 | m = m | m - 1; 23 | n = n ^ m; 24 | return n; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/477. TotalHammingDistance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public : 3 | int totalHammingDistance(vector< int >& nums) { 4 | int res = 0 , n = nums.size(); 5 | for ( int i = 0 ; i < 32 ; ++ i) { 6 | int cnt = 0 ; 7 | for ( int num: nums) { // counts set bits at pos i from right 8 | if (num & ( 1 << i)) ++ cnt; 9 | } 10 | res += cnt * (n- cnt); // #setBit * #UnsetBit 11 | } 12 | return res; 13 | } 14 | }; 15 | 16 | //4: 0 1 0 0 17 | 18 | //14: 1 1 1 0 19 | 20 | //2: 0 0 1 0 21 | 22 | //1: 0 0 0 1 23 | 24 | //By observing the above binary form, Imp rule identified here is 25 | //Number of Setbit * number of unsetbit 26 | -------------------------------------------------------------------------------- /C++/50. Pow-function.cpp: -------------------------------------------------------------------------------- 1 | /*To implement pow(x, n), which calculates x raised to the power n (i.e. xn). 2 | 3 | 4 | For Example: 5 | 6 | Input: x = 2.00000, n = 10 7 | Output: 1024.00000*/ 8 | 9 | class Solution { 10 | public: 11 | 12 | double myPow(double x, int n) 13 | { 14 | double c=n; 15 | return pow(x,c); // using pow function to get x^n 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/504. Base 7.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string convertToBase7(int num) { 4 | //initialization 5 | int n=0,x,y; 6 | string s=""; 7 | y=num; 8 | //Base case 9 | if(num==0){s+="0";return s;} 10 | //Dividing a number unless it is reduced to zero 11 | while(num!=0){ 12 | x=abs(num%7); 13 | num=num/7; 14 | s+=(x+48); 15 | } 16 | if(y<0)s=s+"-"; 17 | //reversing the number string 18 | reverse(s.begin(), s.end()); 19 | return s; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/532. K-diffPairsInAnArray.cpp: -------------------------------------------------------------------------------- 1 | //If k==0,check how many number of elements are repeated 2 | /*Else for each unique number num in the set of given integers check whether num+k is present.If it is there,then increment finalval*/ 3 | 4 | class Solution { 5 | public: 6 | int findPairs(vector& nums, int k) { 7 | set s; 8 | int n=nums.size(),fval=0; 9 | for(int i=0;i mp; 14 | for(int i=0;i ::iterator it; 25 | for(it=s.begin();it!=s.end();it++) 26 | { 27 | int val=(*it); 28 | 29 | if(s.find(k+val)!=s.end()) 30 | fval++; 31 | 32 | } 33 | return fval; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /C++/540. SingleElementInASortedArray.cpp: -------------------------------------------------------------------------------- 1 | // The idea is that by, cumulatively, XORing all elements in an array, the result is the single element in the array. 2 | 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int singleNonDuplicate(vector & nums){ 9 | int answer = 0; 10 | for(auto e : nums) answer ^= e; 11 | return answer; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /C++/561. Array Partition I.cpp: -------------------------------------------------------------------------------- 1 | /*Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum. */ 2 | class Solution { 3 | public: 4 | int arrayPairSum(vector& a) { 5 | sort(a.begin(), a.end()); 6 | long long int sum = 0, i; 7 | for (i = 0; i < a.size(); i += 2) 8 | sum += a[i]; 9 | return sum; 10 | } 11 | }; -------------------------------------------------------------------------------- /C++/589.N-aryTreePreorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector preorder(Node* root) { 4 | vector result; 5 | stack s; 6 | 7 | if(root==NULL) 8 | return result; 9 | 10 | //pushing the root node into stack 11 | s.push(root); 12 | 13 | //updating the stack and pushing the values in result till the stack is not empty 14 | while(!s.empty()) 15 | { 16 | //creating a temporary node pointing to the top of stack 17 | Node* temp = s.top(); 18 | 19 | //pushing the value of temp node into the result vector 20 | result.push_back(temp->val); 21 | 22 | //popping the current value in the stack which was pushed into the result vector 23 | s.pop(); 24 | 25 | //iterating in reverse to push the children of temp node into the stack 26 | for(int i=temp->children.size()-1; i>=0; i--) 27 | { 28 | s.push(temp->children[i]); 29 | } 30 | } 31 | return result; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /C++/617. MergeTwoBinaryTrees.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { 15 | // Return the other tree, if either of the tree is null. 16 | if(!t1) 17 | return t2; 18 | if(!t2) 19 | return t1; 20 | 21 | /* Create a new node, with value as the summation of both the nodes. Attach the left and right 22 | children and recur for them. */ 23 | TreeNode* t = new TreeNode(t1->val + t2->val); 24 | t->left = mergeTrees(t1->left, t2->left); 25 | t->right = mergeTrees(t1->right, t2->right); 26 | return t; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /C++/62.UniquePaths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePaths(int m, int n) { 4 | /* I am declaring a variable here which stores the no. of unique paths 5 | from start to finish, depending upon which index we are at. 6 | If the Finish point is at [2,2] and the Start point is at [0,0], 7 | we can go to index from Finish taking 2 unique paths. We use this 8 | information to further see how we can go from [3,3] to [0,0] or for that 9 | matter, from [m,n] to Start! 10 | */ 11 | 12 | int path[m][n]; 13 | int i, j; 14 | 15 | for(i=0; i>1; 26 | 27 | while(n>0) { 28 | int current = n%2; 29 | if(current == last) { 30 | return false; 31 | } 32 | 33 | last = current; 34 | n=n>>1; 35 | } 36 | return true; 37 | } 38 | 39 | }; 40 | -------------------------------------------------------------------------------- /C++/7. Reverse_Integer.cpp: -------------------------------------------------------------------------------- 1 | /* Program name :- Reverse_Integer.cpp 2 | this program will receive any 3 digit number whether it is positive or negative and convert it into its reversed form or reverse its digits , 3 | and this program also works if the situation overflows. 4 | */ 5 | 6 | 7 | public class Solution { 8 | 9 | public static int reverse(int x) { 10 | int ret = 0; 11 | boolean zero = false; 12 | while (!zero) { 13 | ret = ret * 10 + (x % 10); 14 | x /= 10; 15 | if(x == 0){ 16 | zero = true; 17 | } 18 | } 19 | return ret; 20 | } 21 | 22 | public static void main(String[] args) { 23 | int s = 1000000003; 24 | System.out.println(reverse(s)); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /C++/7.ReverseInteger.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reverse(int x) { 4 | long a,rev; 5 | rev=0; 6 | while(x!=0) 7 | { 8 | a=x%10; //storing the remainder(or the last digit of a number) in integer a 9 | x=x/10; //reducing the original number to its quotient in each step 10 | 11 | if(rev>INT_MAX/10 || (rev==INT_MAX/10 && a>7)) //overflow condition 12 | return 0; 13 | if(rev root->val) { 23 | root->right = insertIntoBST(root->right, val); 24 | } 25 | if(val < root->val) { 26 | root->left = insertIntoBST(root->left, val); 27 | } 28 | return root; 29 | } 30 | }; -------------------------------------------------------------------------------- /C++/705.DesignHashSet.cpp: -------------------------------------------------------------------------------- 1 | class MyHashSet { 2 | public: 3 | //creating a vector for storing all the possible hash values 4 | vector hash; 5 | MyHashSet() { 6 | //resizing this vector to a value given in the constraints 7 | hash.resize(1e6+1, false); 8 | } 9 | 10 | void add(int key) { 11 | //marking the key as true to indicate that it has been inserted 12 | hash[key] = true; 13 | } 14 | 15 | void remove(int key) { 16 | //marking the key as false to indicate it's not in the hash set 17 | hash[key] = false; 18 | } 19 | 20 | bool contains(int key) { 21 | //returning the value of this key. If the key exists, it will return true, else false 22 | return hash[key]; 23 | } 24 | }; 25 | 26 | /* 27 | TC: O(1) 28 | SC: O(n) 29 | */ 30 | 31 | /** 32 | * Your MyHashSet object will be instantiated and called as such: 33 | * MyHashSet* obj = new MyHashSet(); 34 | * obj->add(key); 35 | * obj->remove(key); 36 | * bool param_3 = obj->contains(key); 37 | */ 38 | -------------------------------------------------------------------------------- /C++/709. To Lower Case.cpp: -------------------------------------------------------------------------------- 1 | // problem - 709. To Lower Case 2 | 3 | /* 4 | Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase. 5 | */ 6 | 7 | class Solution { 8 | public: 9 | string toLowerCase(string& str) { 10 | for(int i=0; i 64 && str[i] < 91) str[i] = (str[i] + 32); 14 | } 15 | 16 | return str; 17 | } 18 | }; 19 | 20 | // Time Complexity = O(n) [n is the length of the given string] 21 | // Space Complexity = O(1) -------------------------------------------------------------------------------- /C++/72. Edit_Distance.cpp: -------------------------------------------------------------------------------- 1 | //Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. 2 | 3 | //You have the following 3 operations permitted on a word: 4 | 5 | //Insert a character 6 | //Delete a character 7 | //Replace a character 8 | //The code is basically recursion with memeotization. it will comapre to find the minimum operation. 9 | 10 | class Solution { 11 | public: 12 | int dp[1002][1002]; 13 | int edit(string word1,string word2,int m,int n) 14 | { 15 | // cout<& cost) { 15 | int i; 16 | int n = cost.size(); 17 | i = n - 3; 18 | while(i >= 0){ 19 | cost[i] += min(cost[i+1], cost[i+2]); 20 | i--; 21 | } 22 | 23 | 24 | return min(cost[0], cost[1]); 25 | 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /C++/75.SortColors.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. 3 | 4 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 5 | */ 6 | 7 | class Solution { 8 | public: 9 | void sortColors(vector& nums) { 10 | sort(nums.begin(),nums.end()); 11 | } 12 | }; 13 | /* 14 | Sample Tests: 15 | 16 | Input: nums = [2,0,2,1,1,0] 17 | Output: [0,0,1,1,2,2] 18 | 19 | Input: nums = [2,0,1] 20 | Output: [0,1,2] 21 | 22 | Input: nums = [0] 23 | Output: [0] 24 | 25 | Input: nums = [1] 26 | Output: [1] 27 | */ 28 | -------------------------------------------------------------------------------- /C++/766. Toeplitz Matrix.cpp: -------------------------------------------------------------------------------- 1 | // problem - 766. Toeplitz Matrix 2 | 3 | /* 4 | Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false. 5 | 6 | A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. 7 | */ 8 | 9 | class Solution { 10 | public: 11 | bool isToeplitzMatrix(vector>& matrix) { 12 | int n = matrix.size(); 13 | int m = matrix[0].size(); 14 | 15 | if(m == 1 || n == 1) return true; 16 | 17 | // traversing diagonally 18 | for(int i=1; i& arr) { 11 | int low = 0, high = arr.size() - 1; 12 | 13 | while (low < high) { 14 | int mid = low + (high - low)/2; 15 | 16 | if (arr[mid] < arr[mid + 1]) { 17 | low = mid + 1; 18 | } else { 19 | high = mid; 20 | } 21 | } 22 | 23 | return low; 24 | } 25 | }; -------------------------------------------------------------------------------- /C++/881.BoatsToSavePeople.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numRescueBoats(vector& people, int limit) { 4 | 5 | //arranging the people in increasing order of their weights; the idea is to pair a light weighted person 6 | //with a heavy person 7 | sort(begin(people), end(people)); 8 | 9 | //count for number of boats 10 | int count = 0; 11 | 12 | //for keeping a track of people from the heavier end 13 | int index = people.size()-1; 14 | 15 | for(int i=0; i<=index; ) 16 | { 17 | //people[i]<=limit, so if a (light + heavy)pair <= limit, increment i 18 | if(people[i] + people[index]<=limit) 19 | i++; 20 | //index will be decremented either way because the weight of 1 person is not going beyond limit so 21 | //1 person per boat is a possibility and we increase the count 22 | index--; 23 | 24 | count++; 25 | } 26 | return count; 27 | } 28 | }; 29 | 30 | /* 31 | TC = O(NLogN) 32 | SC = O(1) 33 | */ 34 | -------------------------------------------------------------------------------- /C++/9. Palindrome Number.cpp: -------------------------------------------------------------------------------- 1 | /*To determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.*/ 2 | 3 | class Solution 4 | { 5 | public: 6 | bool isPalindrome(int x) 7 | { 8 | if (x < 0) // to check whether x is negative 9 | return false; 10 | 11 | // for positive x values 12 | 13 | // Storing digits of x into vector a 14 | vector a; // declaration of vector a 15 | while (x != 0) 16 | { 17 | a.push_back(x % 10); 18 | x = x / 10; 19 | } 20 | 21 | bool flag = true; 22 | int n = a.size(); 23 | for (int i = 0; i < n / 2; i++) // start of loop 24 | { 25 | if (a[i] != a[n - i - 1]) 26 | { 27 | flag = false; 28 | break; // breaks from the loop when x is not palindrome 29 | } 30 | } 31 | 32 | return flag; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /C++/905. SortArrayByParity.cpp: -------------------------------------------------------------------------------- 1 | //Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. 2 | //Check if odd, erase it from the array and push the element at the back 3 | 4 | class Solution { 5 | public: 6 | vector sortArrayByParity(vector& A) { 7 | int n=A.size(); 8 | int i=0,count=0; 9 | while(count dp(n+1,0); 10 | dp[0]=1; 11 | if(s[0] != '0') 12 | dp[1]=1; 13 | 14 | for(int i=2;i<=n;i++){ 15 | if(s[i-1] != '0') 16 | dp[i]+=dp[i-1]; 17 | if(s[i-2] =='1' || (s[i-2] =='2' && s[i-1]<='6')) 18 | dp[i]+=dp[i-2]; 19 | } 20 | return dp[n]; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /C++/922. SortArrayByParityII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even. 3 | Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even. 4 | You may return any answer array that satisfies this condition. 5 | 6 | Example 1: 7 | 8 | Input: [4,2,5,7] 9 | Output: [4,5,2,7] 10 | Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. 11 | */ 12 | 13 | class Solution { 14 | public: 15 | vector sortArrayByParityII(vector& A) { 16 | int n = A.size(); 17 | 18 | vector B(n,0); 19 | int j=0,k=1; 20 | for(int i=0;ileft, L, R); 27 | 28 | // compute right subtree's value 29 | postOrderTraversal(root->right, L, R); 30 | 31 | // if L <= node's value <= R then only add it to sum 32 | // otherwise do nothing 33 | if (root->val >= L && root->val <= R) 34 | sum += root->val; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /C++/940. DistinctSubseqII.cpp: -------------------------------------------------------------------------------- 1 | /* Given a string S, count the number of distinct, non-empty subsequences of S . 2 | 3 | Since the result may be large, return the answer modulo 10^9 + 7. */ 4 | 5 | // Import neccessary header files. 6 | 7 | class Solution { 8 | public: 9 | int distinctSubseqII(string S) { 10 | 11 | S = "$" + S; 12 | int n = S.length(); 13 | vector dp(n, 0); 14 | vector lastPos(26, -1); 15 | 16 | int mod = 1e9 + 7; 17 | 18 | for(int i = 0; i < n; i++) { 19 | if(i == 0) { // empty string 20 | dp[i] = 1; 21 | continue; 22 | } 23 | 24 | dp[i] = 2 * dp[i - 1] % mod; 25 | if(lastPos[S[i] - 'a'] != -1) { 26 | dp[i] = dp[i] % mod - dp[lastPos[S[i] - 'a'] - 1] % mod + mod; 27 | } 28 | 29 | lastPos[S[i] - 'a'] = i; 30 | } 31 | 32 | // for removing $ 33 | return dp[n - 1] % mod - 1; 34 | } 35 | }; -------------------------------------------------------------------------------- /C++/941. ValidMountainArray.cpp: -------------------------------------------------------------------------------- 1 | //Given an array A of integers, return true if and only if it is a valid mountain array. 2 | //Runtime beats 82.32% of cpp submission 3 | //Find the peak(largest number), check whether it is strictly decreasing/increasing from the peak 4 | 5 | class Solution { 6 | public: 7 | bool validMountainArray(vector& A) { 8 | int j=0,k=0; 9 | int large=0; 10 | if(A.size()<3) 11 | return false; 12 | 13 | for(int i=0;i=A[k+1]) 22 | return false; 23 | k++; 24 | } 25 | j=large; 26 | while(j& nums) { 14 | // Iterate over nums 15 | for(int i=0; i> kClosest(vector>& points, int K) { 12 | vector> vec; 13 | for(int i=0;i> f;//final points vector 19 | for(int i=0;i& nums) { 4 | 5 | //sorting the array 6 | sort(begin(nums), end(nums)); 7 | 8 | //iterating from end to check if the lengths satisfy the triangle condition 9 | for(int i=nums.size()-3; i>=0; i--) 10 | { 11 | if(nums[i] + nums[i+1] > nums[i+2]) 12 | return (nums[i]+nums[i+1]+nums[i+2]); 13 | } 14 | return 0; 15 | } 16 | }; 17 | 18 | /* 19 | Explanation through an example: 20 | [3,2,3,4] = [2,3,3,4] //sorted 21 | i= 0,1,2,3 , range = 0 to 3 22 | //iterate from last 3 val to 0 since array is sorted, chances are that the sum of last 3 lengths 23 | //(forming a valid triangle) will give the largest perimeter 24 | 25 | i=1, nums[1] + nums [2] = 3+3=6 > nums[3]=4, the condition is true, so perimeter =3+3+4=10 26 | 27 | TC=O(nlogn), SC=O(1) 28 | */ 29 | -------------------------------------------------------------------------------- /C++/977. SquaresOfASortedArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers A sorted in non-decreasing order, 3 | return an array of the squares of each number, 4 | also in sorted non-decreasing order. 5 | 6 | https://leetcode.com/problems/squares-of-a-sorted-array/ 7 | 8 | */ 9 | 10 | class Solution 11 | { 12 | public: 13 | vector sortedSquares(vector &A) 14 | { 15 | int len = A.size(); 16 | vector B(len); 17 | 18 | for (int i = 0; i < len; i++) 19 | { 20 | B[i] = A[i] * A[i]; 21 | } 22 | 23 | sort(B.begin(), B.end()); 24 | return B; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/991.BrokenCalculator.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int brokenCalc(int startValue, int target) { 4 | int ops = 0; 5 | 6 | while(target > startValue) 7 | { 8 | /*we are deliberately making the target value even if it's odd because the number of operations reduce 9 | if we multiply or divide instead of repeatedly adding values, 10 | e.g., 1+1+1+1+1=5(4 operations), 1*5=5(1 operation)! 11 | */ 12 | if(target%2==1) 13 | target++; 14 | //divide the target by 2 if it's even 15 | else 16 | target=target/2; 17 | 18 | ops++; 19 | } 20 | 21 | //startValue - target is the number of additions(+1s) we will need to reach the startValue 22 | ops = ops + (startValue - target); 23 | return ops; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /C++/anagram.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | string s1; 7 | string s2; 8 | cin>>s1>>s2; 9 | if(s1.length()!=s2.length()){ 10 | cout<<"not anagram"; 11 | return 0; 12 | } 13 | int array[26]; 14 | for(int i=0;i<26;i++){ 15 | array[i]=0; 16 | } 17 | for(int i=0;i map = new HashMap<>(); 9 | int[] res = new int[2]; 10 | for (int i = 0; i < nums.length; i++) { 11 | if (map.containsKey(target - nums[i])) { 12 | res[0] = map.get(target - nums[i]); 13 | res[1] = i; 14 | return res; 15 | } else { 16 | map.put(nums[i], i); 17 | } 18 | } 19 | return res; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Java/1041. RobotBoundedInCircle.java: -------------------------------------------------------------------------------- 1 | /* 2 | On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions: 3 | 4 | "G": go straight 1 unit; 5 | "L": turn 90 degrees to the left; 6 | "R": turn 90 degress to the right. 7 | The robot performs the instructions given in order, and repeats them forever. 8 | 9 | Return true if and only if there exists a circle in the plane such that the robot never leaves the circle. 10 | */ 11 | 12 | class Solution { 13 | public boolean isRobotBounded(String ins) { 14 | int x = 0, y = 0, i = 0, d[][] = {{0, 1}, {1, 0}, {0, -1}, { -1, 0}}; 15 | for (int j = 0; j < ins.length(); ++j) 16 | if (ins.charAt(j) == 'R') 17 | i = (i + 1) % 4; 18 | else if (ins.charAt(j) == 'L') 19 | i = (i + 3) % 4; 20 | else { 21 | x += d[i][0]; y += d[i][1]; 22 | } 23 | return x == 0 && y == 0 || i > 0; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Java/1050. PrimeFactors.java: -------------------------------------------------------------------------------- 1 | /** 2 | *Implemented a basic program to calculate the prime factors of a given number (see prime factors kata). 3 | *The given number should be just an integer and the program would return a list of the prime factors of the given integer. 4 | */ 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | class Solution { 10 | public static List factorsOf(int n) 11 | { 12 | ArrayList factors = new ArrayList<>(); 13 | 14 | for (int divisor = 2; n > 1; divisor++) 15 | for (; n % divisor == 0; n /= divisor) 16 | factors.add(divisor); 17 | 18 | return factors; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Java/1051. HeightChecker.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Solution { 3 | public int heightChecker(int[] heights) { 4 | int[] sortHeights=new int[heights.length]; 5 | int count=0; 6 | for(int i=0;iindex;i--){ 5 | arr[i]=arr[i-1]; 6 | } 7 | arr[index]=0; 8 | } 9 | 10 | public void duplicateZeros(int[] arr) { 11 | 12 | int len=arr.length; 13 | 14 | for(int i=0;i= 'A' && ch <= 'Z') 19 | visit[ch - 'A'] = true; 20 | 21 | // when ch is a - z 22 | if (ch >= 'a' && ch <= 'z') 23 | visit[ch - 'a'] = true; 24 | } 25 | 26 | for (int i = 0; i < visit.length; i++) 27 | if (!visit[i]) 28 | return false; 29 | 30 | return true; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Java/121. BestTimeToBuyAndSell.java: -------------------------------------------------------------------------------- 1 | /* Say you have an array for which the ith element is the price of a given stock on day i. 2 | If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. 3 | Note that you cannot sell a stock before you buy one. 4 | 5 | Example 1: 6 | Input: [7,1,5,3,6,4] 7 | Output: 5 8 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 9 | Not 7-1 = 6, as selling price needs to be larger than buying price. 10 | */ 11 | 12 | class Solution { 13 | public int maxProfit(int[] prices) { 14 | int lsf = Integer.MAX_VALUE; /* least so far */ 15 | int pist = 0; /* Profit if sold today */ 16 | int op = 0; /* overall profit */ 17 | 18 | for(int i=0; i op){ 25 | op = pist; 26 | } 27 | } 28 | 29 | return op; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Java/1295. Find_Number_with_even.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | int findDigit(int n){ 4 | int result=0; 5 | while(n/10 > 0){ 6 | n=n/10; 7 | result++; 8 | } 9 | return result-1; 10 | } 11 | 12 | public int findNumbers(int[] nums) { 13 | 14 | int count=0; 15 | int len=0; 16 | for(int i = 0 ; i < nums.length ; i++){ 17 | len=findDigit(nums[i]); 18 | if(len%2 == 0){ 19 | count++; 20 | } 21 | } 22 | return count; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Java/1299.ReplaceElementswithGreatestElementonRightSide.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findGreatest(int[] arr, int key){ 3 | int len=arr.length; 4 | int max=arr[len-1]; 5 | for(int i=len-1;i>key;i--){ 6 | if(arr[i]>max){ 7 | max=arr[i]; 8 | } 9 | } 10 | return max; 11 | } 12 | 13 | public int[] replaceElements(int[] arr) { 14 | int len=arr.length; 15 | 16 | 17 | for(int i=0;i keys= new Hashtable<>(); 7 | for(int i=0;i 0 ? 1 : 0; 32 | rDistinct += rh[i] > 0 ? 1 : 0; 33 | } 34 | 35 | return lDistinct == rDistinct; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Java/198. HouseRobber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Since we are not allowed to rob two adjacent houses, we keep two variables pre and cur. 3 | During the i-th loop, pre records the maximum profit that we do not rob the i - 1-th house and thus the current house (the i-th house) can be robbed 4 | while cur records the profit that we have robbed the i - 1-th house. 5 | 6 | The code is as follows. 7 | 8 | Java 9 | */ 10 | 11 | 12 | class Solution { 13 | public int rob(int[] nums) { 14 | int pre = 0, cur = 0; 15 | for (int num : nums) { 16 | final int temp = Integer.max(pre + num, cur); 17 | pre = cur; 18 | cur = temp; 19 | } 20 | return cur; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Java/215.KthElementInAnArray.java: -------------------------------------------------------------------------------- 1 | /** 2 | * The challenge no.215 asks for the kth largest element of an array to be returned. 3 | * 4 | * To solve this problem, the array has to be sorted and then the Kth element from the top will be returned. 5 | * 6 | * To save some processing time, the array only gets sorted for K elements which is slightly faster than sorting all elements. 7 | */ 8 | //Solving this question using a min heap of size K. 9 | //We start adding elements in the priority queue and when the size exceeds K we pop the topmost element(minimum element). 10 | //This way when we are done inserting all the array elements in the priority queue and simultaneously popping according to priority, 11 | //At the end, we are left with a priority queue of size K and the topmost element is the Kth largest. 12 | class Solution { 13 | public int findKthLargest(int[] nums, int k) { 14 | PriorityQueue pq = new PriorityQueue<>(); 15 | for(int ele: nums) 16 | { 17 | pq.add(ele); 18 | if(pq.size()>k) 19 | pq.remove(); 20 | } 21 | 22 | return pq.peek(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Java/22. generatePara.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Solution { 3 | void solve(int open, int close , String op,ArrayList res) 4 | { 5 | if(open==0 && close==0) 6 | { 7 | res.add(op); 8 | return; 9 | } 10 | if(open!=0) 11 | { 12 | String op1=op+"("; 13 | // open--; 14 | solve(open-1,close,op1,res); 15 | } 16 | if(close>open) 17 | { 18 | String op2=op+")"; 19 | // close--; 20 | solve(open,close-1,op2,res); 21 | } 22 | return ; 23 | } 24 | public List generateParenthesis(int n) { 25 | ArrayList res=new ArrayList<>(); 26 | int open = n; 27 | int close = n ; 28 | String op = ""; 29 | solve(open,close,op,res); 30 | 31 | return res; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Java/26. RemoveDuplicatesfromSortedArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | int len=nums.length; 4 | int k=0; 5 | 6 | for(int i=1;i= 0) System.arraycopy(arr, key + 1, arr, key, len - 1 - key); //add elements to array 6 | } 7 | 8 | public int removeElement(int[] nums, int val) { 9 | int i = 0; // declaration variable 10 | int len = nums.length; //declaration array lenght 11 | 12 | for(int j = 0; j < nums.length; j++){ //go through the array elements with the for loop 13 | if(nums[j] != val) { //if statement : actual value of array != input value 14 | nums[i++] = nums[j]; // compare with other elements of array 15 | len--; //decrement lenght 16 | } 17 | } 18 | return nums.length-len; 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Java/283. MoveZeroes.java: -------------------------------------------------------------------------------- 1 | /* 2 | 283 | MOVE ZEROES | EASY PROBLEM 3 | 4 | Problem Description: 5 | Given an array of integers, move all the 0's to the end of the array, while 6 | maintaining the relative order of elements and doing this operation in-place 7 | 8 | Conditions: 9 | 1. Preserve relative order 10 | 2. In place operation 11 | 12 | Optimization Criteria: 13 | 1. Minimize extra space taken(no copy of the array allowed) 14 | 2. Minimize operations 15 | 16 | Solution : Insert the non-zero number first, then insert the zeroes. 17 | */ 18 | 19 | public class Solution{ 20 | public void moveZeroes(int[] nums){ 21 | int index=0; 22 | for (int i=0;i= 1 && A[i] <= n && A[i] != A[A[i] - 1]) { 16 | swap(A, i, A[i] - 1); 17 | } else { 18 | i++; 19 | } 20 | } 21 | 22 | for (i = 0; i < n; i++) { 23 | if (A[i] != i + 1) { 24 | return i + 1; 25 | } 26 | } 27 | 28 | return A[n - 1] + 1; 29 | } 30 | 31 | private void swap(int[] A, int i, int j) { 32 | int temp = A[i]; 33 | A[i] = A[j]; 34 | A[j] = temp; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Java/414.ThirdMaximumNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | class Solution { 3 | public int thirdMax(int[] nums) { 4 | int fmax, smax, tmax; 5 | int len=nums.length; 6 | boolean flag=false; 7 | fmax=Integer.MIN_VALUE; 8 | smax=Integer.MIN_VALUE; 9 | tmax=Integer.MIN_VALUE; 10 | 11 | for(int i=0;ifmax){ 16 | tmax=smax; 17 | smax=fmax; 18 | fmax=nums[i]; 19 | } 20 | else if(nums[i]!=fmax && nums[i]>smax){ 21 | tmax=smax; 22 | smax=nums[i]; 23 | } 24 | else if(nums[i]!=smax && nums[i]tmax){ 25 | tmax=nums[i]; 26 | } 27 | } 28 | 29 | if(smax==tmax){ 30 | return fmax; 31 | }else if(tmax!=Integer.MIN_VALUE || flag){ 32 | return tmax; 33 | }else{ 34 | return fmax; 35 | } 36 | 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Java/421.MaximumXORofTwoNumbersInAnArray.java: -------------------------------------------------------------------------------- 1 | // Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 ≤ i ≤ j < n. 2 | class Solution { 3 | public int findMaximumXOR(int[] nums) { 4 | int max = 0, mask = 0; 5 | for(int i = 31; i >= 0; i--){ 6 | mask = mask | (1 << i); 7 | Set set = new HashSet<>(); 8 | for(int num : nums){ 9 | set.add(num & mask); 10 | } 11 | int tmp = max | (1 << i); 12 | for(int prefix : set){ 13 | if(set.contains(tmp ^ prefix)) { 14 | max = tmp; 15 | break; 16 | } 17 | } 18 | } 19 | return max; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Java/48. RotateImage.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void rotate(int[][] matrix) { 3 | int n=matrix.length; 4 | for(int layer=0; layer top 12 | matrix[layer][i] = matrix[last-offset][first]; 13 | 14 | //bottom -> left 15 | matrix[last-offset][first] = matrix[last][last-offset]; 16 | 17 | //right -> bottom 18 | matrix[last][last-offset] = matrix[i][last]; 19 | 20 | //top -> right 21 | matrix[i][last] = top; 22 | } 23 | } 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Java/485. Max_Consecutive_ones.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findMaxConsecutiveOnes(int[] nums) { 3 | int consec=0; 4 | int result=0; 5 | for(int i = 0 ; i < nums.length;i++){ 6 | if(nums[i]==1){ 7 | consec++; 8 | if(result 0; i /=2) { 15 | if( (i % 2 == 1) ){ 16 | answer = answer * product; 17 | } 18 | product *= product; 19 | } 20 | 21 | return answer; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java/560. Subarray Sum Equals K.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. 3 | 4 | Example 1: 5 | Input:nums = [1,1,1], k = 2 6 | Output: 2 7 | 8 | Example 2: 9 | Input:nums = [0,0,0,0], k = 0 10 | Output: 10 11 | */ 12 | 13 | class Solution { 14 | public int subarraySum(int[] nums, int k) { 15 | int count = 0, sum = 0; 16 | HashMap < Integer, Integer > map = new HashMap < > (); 17 | map.put(0, 1); 18 | for (int i = 0; i < nums.length; i++) { 19 | sum += nums[i]; 20 | if (map.containsKey(sum - k)) 21 | count += map.get(sum - k); 22 | map.put(sum, map.getOrDefault(sum, 0) + 1); 23 | } 24 | return count; 25 | } 26 | } 27 | 28 | 29 | 30 | /* Explantion/Approach: 31 | The trick here is to maintain HashMap which stores frequency of prefix sums as key and its freuqency as value. The question if kindof extension of zero sum subarray problem. See this video: https://www.youtube.com/watch?v=PSpuM9cimxA (zero sum subarray). 32 | */ -------------------------------------------------------------------------------- /Java/62. UniquePath.java: -------------------------------------------------------------------------------- 1 | /* 2 | The idea is to use a 2D array to keep track of the total possible ways to enter specific block. 3 | Since we can only go "DOWN" and "RIGHT", therefore each block could be entered from both "ABOVE" and "LEFT", therefore adding up their total ways would give the total ways for current block. 4 | In order to save the hassles in the future, it's easier that we initialize the array 5 | which is why dp[1][0]=1 6 | 7 | Following is the code 8 | 9 | */ 10 | public static int uniquePaths(int m, int n) { 11 | int[][] dp = new int[n + 1][m + 1]; 12 | dp[1][0] = 1; 13 | for (int i = 1; i <= n; i++) { 14 | for (int j = 1; j <= m; j++) { 15 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 16 | } 17 | } 18 | return dp[n][m]; 19 | } 20 | -------------------------------------------------------------------------------- /Java/621. Task Scheduler.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int leastInterval(char[] tasks, int n) { 3 | int[] freq = new int[26]; 4 | 5 | int maxFreq = 0; 6 | for (char task : tasks) { 7 | ++freq[task - 'A']; 8 | maxFreq = Integer.max(maxFreq, freq[task - 'A']); 9 | } 10 | 11 | int numsWithMaxFreq = 0; 12 | for (int i = 0; i < 26; ++i) { 13 | if (maxFreq == freq[i]) 14 | ++numsWithMaxFreq; 15 | } 16 | 17 | // if AAABBBCCDDE, n=3 => ABxxABxxAB is the frame with size 10 18 | int frameSize = Integer.max(numsWithMaxFreq, n + 1) * (maxFreq - 1) + numsWithMaxFreq; 19 | int occupied = numsWithMaxFreq * maxFreq; 20 | int rem = 0; 21 | 22 | for (int i = 0; i < 26; ++i) { 23 | if (freq[i] == maxFreq) 24 | continue; 25 | rem += freq[i]; 26 | } 27 | 28 | return Integer.max(frameSize, occupied + rem); 29 | } 30 | } -------------------------------------------------------------------------------- /Java/75.SortColors.java: -------------------------------------------------------------------------------- 1 | /* Solving without using the inbuilt "sorting" function which is given in many programming languages because here we have to sort 'in-place' and in linear time */ 2 | /* The time complexity-O(n) Space complexity-O(1) */ 3 | 4 | 5 | class Solution{ 6 | public void sortColors(int[] nums) { 7 | int p1=0,index=0,p2=nums.length-1; 8 | int temp; 9 | 10 | while(index <= p2){ 11 | if (nums[index]==0){ 12 | temp=nums[index]; 13 | nums[index]=nums[p1]; 14 | nums[p1]=temp; 15 | p1++; 16 | } 17 | if (nums[index]==2){ 18 | temp=nums[index]; 19 | nums[index]=nums[p2]; 20 | nums[p2]=temp; 21 | p2--; 22 | index--; 23 | } 24 | index++; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Java/78. Subsets.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a set of distinct integers, nums, return all possible subsets (the power set). 3 | 4 | Note: The solution set must not contain duplicate subsets. 5 | 6 | Example: 7 | 8 | Input: nums = [1,2,3] 9 | Output: 10 | [ 11 | [3], 12 | [1], 13 | [2], 14 | [1,2,3], 15 | [1,3], 16 | [2,3], 17 | [1,2], 18 | [] 19 | ] 20 | */ 21 | 22 | class Solution { 23 | public List> subsets(int[] nums) { 24 | List> lists = new ArrayList<>(); 25 | for(int i=0; i<(1< list = new ArrayList<>(); 27 | for(int j=nums.length-1; j>=0; j--){ 28 | int mask = 1< 0) // dp case when buying ticket for 7 days 15 | dp[i] = Integer.min(dp[i - 7] + costs[1], dp[i]); 16 | else 17 | dp[i] = Integer.min(dp[0] + costs[1], dp[i]); 18 | 19 | if (i - 30 > 0) // dp case when buying ticket for a month (30 days) 20 | dp[i] = Integer.min(dp[i - 30] + costs[2], dp[i]); 21 | else 22 | dp[i] = Integer.min(dp[0] + costs[2], dp[i]); 23 | 24 | ++p; 25 | } 26 | } 27 | // System.out.println(Arrays.toString(dp)); 28 | return dp[days[days.length - 1]]; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Shantanu Kale 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Python/1.TwoSum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | This program takes a list and returns 4 | indices of the two numbers such that they add up to target 5 | """ 6 | def twoSum(self, nums: List[int], target: int) -> List[int]: 7 | hashes = dict() 8 | for i, num in enumerate(nums): 9 | index = target - num 10 | if index not in hashes: 11 | hashes[num] = i 12 | else: 13 | return [hashes[index], i] -------------------------------------------------------------------------------- /Python/1013. PartitionArrayIntoThreePartsWithEqualSum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canThreePartsEqualSum(self, A: List[int]) -> bool: 3 | # Since all the three parts are equal, if we sum all element of arrary it should be a multiplication of 3 4 | # so the sum of each part must be equal to sum of all element divided by 3 5 | quotient, remainder = divmod(sum(A), 3) 6 | 7 | if remainder != 0: 8 | return False 9 | 10 | subarray = 0 11 | partitions = 0 12 | for num in A: 13 | subarray += num 14 | if subarray == quotient: 15 | partitions += 1 16 | subarray = 0 17 | 18 | # Check if it consist at least 3 partitions 19 | return partitions >= 3 -------------------------------------------------------------------------------- /Python/1119. RemoveVowelFromString.py: -------------------------------------------------------------------------------- 1 | # 1119. Remove vowels from strings 2 | # This program removes the vowels from a given string 3 | # 4 | # Example: given 'Hello world', the program returns 'Hll wrld' 5 | 6 | class Solution(object): 7 | def removeVowelsFromString(self, string): 8 | vowels = ('a','e','i','o','u') 9 | new_string = "" 10 | 11 | for s in string: 12 | if s.lower() not in vowels: 13 | new_string += s 14 | 15 | return new_string 16 | -------------------------------------------------------------------------------- /Python/1189. MaximumNumberOfBalloons.py: -------------------------------------------------------------------------------- 1 | #Function maxNumberOfBalloons takes text and count how many words "balloon" can be spelled using distinct letters from text. 2 | from collections import Counter 3 | 4 | class Solution(object): 5 | def maxNumberOfBalloons(self, text): 6 | numberOfLetters = Counter(text) 7 | numberOfLetters['l'] //= 2 8 | numberOfLetters['o'] //= 2 9 | 10 | return min([numberOfLetters[x] for x in 'balon']) 11 | -------------------------------------------------------------------------------- /Python/12. Integer to Roman.py: -------------------------------------------------------------------------------- 1 | """Approach : 2 | 3 | Added all the Roman symbols with its representing values to a dictionary in a descending order. 4 | Then loop over the dictionary and as many of the largest values that can be found in the number to the roman string and leave the remaining part of the number to the smaller symbol.""" 5 | 6 | class Solution: 7 | def intToRoman(self, num: int) -> str: 8 | symbol_value = {"M":1000, "CM":900, "D":500, "CD":400, "C":100, "XC":90, "L":50, "XL":40, "X":10, "IX":9, "V":5 , "IV":4 , "I":1} 9 | roman = "" 10 | for i in symbol_value: 11 | roman += i*(num//symbol_value[i]) 12 | num = num%symbol_value[i] 13 | return roman -------------------------------------------------------------------------------- /Python/122.BestTimeToBuyAndSellStock-II.py: -------------------------------------------------------------------------------- 1 | # 122. Best Time To Buy And Sell Stock II 2 | # Language- Python 3.8.5 64-bit 3 | # Author- @PrithirajN 4 | 5 | #Dynamic Programming Approach 6 | 7 | class Sol(object): 8 | def maxProfit(self, prices): 9 | profit = 0 10 | for i in range(len(prices) - 1): 11 | profit += max(0, prices[i + 1] - prices[i]) 12 | return profit -------------------------------------------------------------------------------- /Python/1232.CheckIfItIsAStraightLine.py: -------------------------------------------------------------------------------- 1 | # Given list of (x, y) coordinates checkStraightLine checks if it forms straight line 2 | # 3 | class Solution: 4 | def checkStraightLine(self, coordinates: List[List[int]]) -> bool: 5 | if len(coordinates) <= 2: 6 | # it is always possible to create line through 2 points (and also 1 and 0) 7 | return True 8 | 9 | x0, y0 = coordinates[0] 10 | x1, y1 = coordinates[1] 11 | 12 | if x0 == x1: 13 | # check if this is vertical line (all x are the same) 14 | return all([x == x0 for x, _ in coordinates]) 15 | 16 | # 2 points define line, so find it's equation y = a*x + b 17 | a = (y0 - y1) / (x0 - x1) 18 | b = y0 - a * x0 19 | 20 | line = lambda x: a*x + b 21 | 22 | #check if all points lies on the line defined by (x0, y0) and (x1, y1) 23 | return all([y == line(x) for x, y in coordinates]) 24 | -------------------------------------------------------------------------------- /Python/13. RomanToInteger.py: -------------------------------------------------------------------------------- 1 | # This program converts the entered roman number to integer . 2 | # We have used the dictionary to ease the input for the desired roman representation of an integer. 3 | 4 | 5 | class Solution(object): 6 | def romanToInt(self, s): 7 | 8 | number = 0 9 | counter = 0 10 | romandict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} 11 | list = ['I', 'V', 'X', 'L', 'C', 'D', 'M'] 12 | for i in range(len(s) - 1): 13 | if list.index(s[i]) < list.index(s[i + 1]): 14 | number += romandict.get(s[i + 1]) 15 | number -= romandict.get(s[i]) 16 | counter += 1 17 | else: 18 | if list.index(s[i]) > list.index(s[i - 1]) and i != 0: 19 | continue 20 | else: 21 | number += romandict.get(s[i]) 22 | counter += 1 23 | if list.index(s[len(s) - 1]) > list.index(s[len(s) - 2]): 24 | return number 25 | else: 26 | number += romandict.get(s[len(s) - 1]) 27 | return number 28 | -------------------------------------------------------------------------------- /Python/1342. NumberOfSteps.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Time: O(bits of num) 3 | Space: O(bits of num) 4 | ''' 5 | 6 | class Solution: 7 | def numberOfSteps (self, num: int) -> int: 8 | 9 | digits = f'{num:b}' 10 | return digits.count('1') - 1 + len(digits) 11 | -------------------------------------------------------------------------------- /Python/1351. CountNegativeNumbersInASortedMatrix.py: -------------------------------------------------------------------------------- 1 | # Given a m * n matrix grid which is sorted in non-increasing order both row-wise and column-wise 2 | # code is to find the number of negative number in each of the sublist. 3 | class Solution: 4 | def countNegatives(self, grid: List[List[int]]) -> int: 5 | count=0 6 | for i in range(len(grid)): 7 | for j in range(len(grid[i])): 8 | if grid[i][j]<0: 9 | count+=1 10 | return count #Return the number of negative numbers in grid. 11 | -------------------------------------------------------------------------------- /Python/1356.SortIntegersByNumberof1Bits.py: -------------------------------------------------------------------------------- 1 | #Problem Statement 2 | # Given an integer array arr. You have to sort the integers in the array in ascending order by the number of 1's in their binary representation 3 | # and in case of two or more integers have the same number of 1's you have to sort them in ascending order. 4 | # Return the sorted array. 5 | #Input : List of numbers separated by a space (eg. 1 2 3 4) 6 | #Output: Sorted list on basis of 1 bits (eg. 1 2 4 3) 7 | arr = list(map(int,input().split())) 8 | res = {} #dictionary that stores the number as key and number of 1 bits as value 9 | for i in arr: 10 | res[i]=bin(i).count("1") #bin function converts the integer to binary form as a string 11 | res_new = sorted(res.items(), key=lambda res: res[1]) #sort the items according to the value(no. of 1 bits) 12 | for i in res_new: 13 | print(i[0], end= " ") #print according to keys(the given integers) 14 | print() -------------------------------------------------------------------------------- /Python/136.SingleNumber.py: -------------------------------------------------------------------------------- 1 | #in this problem we used the Counter object which when we pass a list to it, it returns a dictionnary that has the lists's elemnts as keys and their 2 | # occurences as values 3 | 4 | 5 | from collections import Counter 6 | class Solution(object): 7 | def singleNumber(self, nums): 8 | c=Counter(nums) # in this line we defind c as the dictionnary that has each element of the list as keys and their number of occurences as values 9 | sorted_items=sorted(c.items(), key = lambda x:x[1]) # in this line we sorted that dictionnary based on its values , first item will be the Single Number 10 | return sorted_items[0][0] #since the sorted() function returns a list of key-value pair of sorted dict, our SingleNumber is in the first pair 11 | 12 | -------------------------------------------------------------------------------- /Python/137. SingleNumberII.py: -------------------------------------------------------------------------------- 1 | #Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. 2 | class Solution(object): 3 | def singleNumber(self, nums): 4 | single = 0 5 | original = 0 6 | #First set function is used to find all the unqiue elements and then they are added 7 | for i in set(nums): 8 | single +=i 9 | #Then all the elements of the given list are added 10 | for i in nums: 11 | original +=i 12 | #Variable single conmtains the sum of all unique elements and variable original contains the sum of all elements in the given list.Multiplying the sum of all the unique 13 | #elements by 3 and subtracting it with the sum of all the elements in the original list will leave us with the sum of the single number taken twice. Hence we divide by 2 14 | # to get the single number 15 | return ((single * 3) - original)/2 16 | -------------------------------------------------------------------------------- /Python/14. LongestCommonPrefix.py: -------------------------------------------------------------------------------- 1 | # Write a function to find the longest common prefix string amongst an array of strings. 2 | # 3 | # If there is no common prefix, return an empty string "". 4 | 5 | class Solution(object): 6 | def longestCommonPrefix(self, strs): 7 | """ 8 | :type strs: List[str] 9 | :rtype: str 10 | """ 11 | if not strs: return "" 12 | if len(strs) == 1: return strs[0] 13 | 14 | strs.sort() 15 | p = "" 16 | for x, y in zip(strs[0], strs[-1]): 17 | if x == y: 18 | p += x 19 | else: 20 | break 21 | return p -------------------------------------------------------------------------------- /Python/1436. DestinationCity.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def destCity(self, paths: List[List[str]]) -> str: 3 | p=paths[0][1] 4 | current='' 5 | for i in range(len(paths)): 6 | for l in range(len(paths)): 7 | if i != l: 8 | current =paths[l][0] 9 | if p==current: 10 | p=paths[l][1] 11 | return p #Return the destination city, that is, the city without any path outgoing to another city. 12 | -------------------------------------------------------------------------------- /Python/1470. ShuffleTheArray.py: -------------------------------------------------------------------------------- 1 | # 1470. Shuffle the Array 2 | # Author- @lashewi 3 | 4 | class Solution: 5 | 6 | def shuffle(self, nums: List[int], n: int) -> List[int]: 7 | out = [] 8 | for i in range(n): 9 | out.append(nums[i]) 10 | out.append(nums[i+n]) 11 | return out 12 | -------------------------------------------------------------------------------- /Python/1480. RunningSumof1DArray.py: -------------------------------------------------------------------------------- 1 | # 1480. Running Sum of 1d Array 2 | # Author- @lashewi 3 | 4 | class Solution: 5 | def runningSum(self, nums: List[int]) -> List[int]: 6 | answer_arr = [] 7 | sum_total = 0 8 | 9 | for i in range(0,len(nums)): 10 | sum_total += nums[i] 11 | answer_arr.append(sum_total) 12 | 13 | return answer_arr 14 | -------------------------------------------------------------------------------- /Python/1502.CanMakeArithmeticProgressionFromSequence.py: -------------------------------------------------------------------------------- 1 | #Have to figue out if the given list is in arithmetic progression or not. 2 | class Solution: 3 | def canMakeArithmeticProgression(self, arr: List[int]) -> bool: 4 | arr.sort() 5 | dif=arr[1]-arr[0] 6 | for i in range (2,len(arr)): 7 | d=arr[i]-arr[i-1] 8 | if d!=dif: 9 | return False 10 | return True 11 | -------------------------------------------------------------------------------- /Python/1588. SumofAllOddLengthSubarrays.py: -------------------------------------------------------------------------------- 1 | # Given an array of positive integers arr, calculate the sum of all possible odd-length subarrays. 2 | # A subarray is a contiguous subsequence of the array. 3 | # Return the sum of all odd-length subarrays of arr. 4 | # Author- @lashewi 5 | 6 | class Solution: 7 | def sumOddLengthSubarrays(self, arr: List[int]) -> int: 8 | n = len(arr) 9 | res = 0 10 | 11 | for i in range(n): 12 | even_away = ((i // 2) + 1) * ((n - i - 1) // 2 + 1) 13 | odd_away = ((i + 1) // 2) * ((n - i) // 2) 14 | res += arr[i] * (even_away + odd_away) 15 | 16 | return res 17 | -------------------------------------------------------------------------------- /Python/16. 3SumClosest.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 3 | 4 | Example: 5 | Input: nums = [-1,2,1,-4], target = 1 6 | Output: 2 7 | Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 8 | ''' 9 | 10 | class Solution(object): 11 | def threeSumClosest(self, nums, target): 12 | m = 20000 13 | l = len(nums) 14 | for i in range(0, l-2): 15 | for j in range(i+1, l-1): 16 | for k in range(j+1, l): 17 | s = nums[i] + nums[j] + nums[k] 18 | diff = abs(s-target) 19 | if m>diff: 20 | m = diff 21 | closest_sum = s 22 | return(closest_sum) -------------------------------------------------------------------------------- /Python/162.FindPeakElement.py: -------------------------------------------------------------------------------- 1 | # Function findPeakElement finds receives an array 2 | # and searches for an element considered a peak (greater than its neighbors ) 3 | class Solution(object): 4 | 5 | def findPeakElement(self, arr): 6 | """ 7 | finds the peak element in the array 8 | :param arr: List[int] 9 | :return: the peak element int 10 | """ 11 | 12 | # checks if the array is to small therefore no real need to check 13 | if len(arr) == 1: 14 | return 0 15 | # dealing with two is only a single case 16 | elif len(arr) == 2: 17 | if arr[0] > arr[1]: 18 | return 0 19 | else: 20 | return 1 21 | 22 | # peak is at the beginning 23 | if arr[0] > arr[1]: 24 | return 0 25 | 26 | # goes though the array and finds a peak 27 | for i in range(1, len(arr) - 1): 28 | if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]: 29 | return i 30 | 31 | # peak is at the end 32 | return len(arr) - 1 33 | 34 | -------------------------------------------------------------------------------- /Python/169.MajorityNumber.py: -------------------------------------------------------------------------------- 1 | #Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 2 | class Solution(object): 3 | def majorityElement(self, nums): 4 | tot = len(nums)/2 5 | ls=[] 6 | #First we find the unique element in the list 7 | for i in set(nums): 8 | count = 0 9 | #Then we count the number of occurrences of the element in the list 10 | for j in nums: 11 | if( i == j): 12 | count += 1 13 | #After that we append the unique element and the number of occurences of the element to the list named ls 14 | ls.append([i,count]) 15 | for i in range(len(ls)): 16 | #Here we check occurence of which element is greater than n/2 and return it 17 | if( ls[i][1] > tot): 18 | return ls[i][0] 19 | -------------------------------------------------------------------------------- /Python/17. LetterCombinationsOfAPhoneNumber.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def letterCombinations(self, digits): 3 | """ 4 | :type digits: str 5 | :rtype: List[str] 6 | """ 7 | A={"2":"abc","3":"def","4":"ghi","5":"jkl","6":"mno","7":"pqrs","8":"tuv","9":"wxyz"} 8 | ans=[] 9 | for _ in range(len(digits)): 10 | temp=[] 11 | for i in range(len(A[digits[_]])): 12 | for var in ans: 13 | temp.append(var+A[digits[_]][i]) 14 | if _ is 0: 15 | for a in A[digits[_]]: 16 | temp.append(a) 17 | ans=temp[:] 18 | return ans 19 | 20 | -------------------------------------------------------------------------------- /Python/172. FactorialTrailingZeroes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer n, return the number of trailing zeroes in n!. 3 | 4 | Example 5 | Input: n = 5 6 | Output: 1 7 | Explanation: 5! = 120, one trailing zero. 8 | """ 9 | 10 | # Algorithm explained: 11 | # In the expanded form of facotorial, the occurenses of 5 or its multiples 12 | # contribute to the trailing zeroes. So, first we count the multiples of 5, 13 | # and now we account for the powers of 5, which can be written as 14 | # repeated multiplication of 5 (eg: 25 = 5 x 5, this contributes 2 zeroes), 15 | # so we scale the number down by 5 (eg: 25 beomes 5) and repeat the same 16 | # procedure until there are no multiples of 5. 17 | 18 | 19 | class Solution: 20 | def trailingZeroes(self, n: int) -> int: 21 | if n < 5: 22 | return 0 23 | a = n // 5 24 | return a + self.trailingZeroes(a) 25 | -------------------------------------------------------------------------------- /Python/19. Remove Nth Node From End of List.py: -------------------------------------------------------------------------------- 1 | ''' Approach : 2 | 3 | 1. Add a dummy node that points to the head of the list. 4 | 2. This dummy node will remove the corner cases such as list with one node etc. 5 | 3. Initialise a stack and push the nodes onto it until "n". 6 | 4. Add the padding at the end. 7 | 5. Remove the previous node and assign the head to the next node. 8 | 6. Return the dummy . 9 | ''' 10 | 11 | # Definition for singly-linked list. 12 | # class ListNode: 13 | # def __init__(self, val=0, next=None): 14 | # self.val = val 15 | # self.next = next 16 | 17 | class Solution: 18 | def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: 19 | 20 | if not head or not n: return 21 | 22 | dummy = ListNode() 23 | dummy.next = head 24 | node = dummy 25 | stack = [] 26 | 27 | while node: 28 | stack.append(node) 29 | node = node.next 30 | 31 | stack.append(None) 32 | prev_node = stack[-n - 2] 33 | next_node = stack[-n] 34 | prev_node.next = next_node 35 | return dummy.next 36 | -------------------------------------------------------------------------------- /Python/20. ValidParentheses.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title -> ValidParenthesis (https://leetcode.com/problems/valid-parentheses/) 3 | 4 | Approach for the solution : 5 | 6 | Initialise a hashmap for mapping brackets and a set for opening parentheses. 7 | Use stack to keep track of opening parentheses. 8 | For each character in string, if the first character is in the open_bracket set then 9 | push it onto the stack, check the mapping of closing bracket and if it's there then 10 | pop it out of the stack. 11 | 12 | At the end if the stack is empty then the string is valid otherwise it is not. 13 | 14 | """ 15 | class Solution: 16 | 17 | def isValid(self, s): 18 | 19 | bracket_mapping = {"(": ")", "[": "]", "{": "}"} 20 | 21 | open_bracket = set(["(", "[", "{"]) 22 | 23 | stack = [] 24 | 25 | for char in s: 26 | if char in open_bracket: 27 | stack.append(char) 28 | elif stack and char == bracket_mapping[stack[-1]]: 29 | stack.pop() 30 | else: 31 | return False 32 | 33 | return stack == [] -------------------------------------------------------------------------------- /Python/204. CountPrimes.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Sieve numbers, assume all are prime and eliminate those who have factors 3 | ''' 4 | class Solution(object): 5 | def countPrimes(self, n): 6 | """ 7 | :type n: int 8 | :rtype: int 9 | """ 10 | isPrime = [True] * n 11 | isPrime[:2] = [False, False] 12 | for i in range(2, int(n ** 0.5) + 1): 13 | if isPrime[i]: 14 | isPrime[i * i: n: i] = [False] * len(isPrime[i * i: n: i]) 15 | return sum(isPrime) 16 | 17 | -------------------------------------------------------------------------------- /Python/205.IsomorphicStrings.py: -------------------------------------------------------------------------------- 1 | # Having 2 strings s1, s2 isIsomorphic checks if s1 can be changed into s2 2 | # by replacing letters of s1 3 | class Solution: 4 | def isIsomorphic(self, s1: str, s2: str) -> bool: 5 | if len(s1) != len(s2): 6 | return False 7 | 8 | mapping = {} 9 | 10 | for letter1, letter2 in zip(s1, s2): 11 | if not letter1 in mapping: 12 | mapping[letter1] = letter2 13 | continue 14 | 15 | if mapping[letter1] != letter2: 16 | return False 17 | 18 | return len(mapping) == len(set(mapping.values())) 19 | -------------------------------------------------------------------------------- /Python/21. MergeTwoSortedLists.py: -------------------------------------------------------------------------------- 1 | # Merge two sorted linked lists and return it as a new sorted list. 2 | # The new list should be made by splicing together the nodes of the first two lists. 3 | 4 | # Definition for singly-linked list. 5 | # class ListNode: 6 | # def __init__(self, val=0, next=None): 7 | # self.val = val 8 | # self.next = next 9 | 10 | class Solution: 11 | def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 12 | sorted_list = result = ListNode(None) 13 | while l1 and l2: 14 | if l1.val < l2.val: 15 | result.next = l1 16 | l1 = l1.next 17 | else: 18 | result.next = l2 19 | l2 = l2.next 20 | result = result.next 21 | result.next = l1 or l2 22 | return sorted_list.next -------------------------------------------------------------------------------- /Python/215.KthLargestElementInAnArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Goal: Finding the Kth largest element in an array. 3 | 4 | Procedure: 5 | -> Creating a min heap. 6 | -> Finding K number of largest elements 7 | -> Returning the Kth element, that is, the last element from the list found in second step. 8 | 9 | Input: 10 | First entering the array. 11 | Second entering the K value. 12 | 13 | Output: 14 | A single output returning the Kth largest element of the array. 15 | 16 | 17 | Examples: 18 | Input: 3 2 1 5 6 4 19 | 2 20 | 21 | Output: 5 22 | 23 | 24 | Input: 3 2 3 1 2 4 5 5 6 25 | 4 26 | 27 | Output: 4 28 | """ 29 | 30 | import heapq 31 | class Solution: 32 | def findKthLargest(nums, k): 33 | heapq.heapify(nums) 34 | res = heapq.nlargest(k,nums) 35 | return res[len(res)-1] 36 | 37 | arr = [int(w) for w in input().strip().split(',')] 38 | k = int(input()) 39 | print(Solution.findKthLargest(arr, k)) 40 | -------------------------------------------------------------------------------- /Python/217.ContainsDuplicate.py: -------------------------------------------------------------------------------- 1 | # Function findPeakElement finds receives an array and checks if 2 | # the array contains a duplicate of two numbers 3 | class Solution(object): 4 | 5 | def ContainsDuplicate(self, arr): 6 | """ 7 | checks if the array contains a duplicate 8 | :param arr: List[int] a list of numbers 9 | :return: True or False if it contains a duplicate 10 | """ 11 | 12 | # a set to contains numbers we have seen 13 | taken_numbers = {} 14 | 15 | # goes through all values in the arr 16 | for i in arr: 17 | # checks if the number has already been seen 18 | if i in taken_numbers: 19 | return True 20 | # adds the number since it hasn't been seen 21 | else: 22 | taken_numbers[i] = i 23 | 24 | # we have not seen any duplicates 25 | return False 26 | -------------------------------------------------------------------------------- /Python/225.ImplementStackUsingQueues.py: -------------------------------------------------------------------------------- 1 | # Implementation of stack datastructure (LIFO) using one FIFO queue 2 | 3 | from collections import deque 4 | 5 | class MyStack: 6 | 7 | def __init__(self): 8 | """ 9 | Initialize your data structure here. 10 | """ 11 | self.queue = deque() 12 | 13 | def push(self, x: int) -> None: 14 | """ 15 | Push element x onto stack. 16 | """ 17 | size = len(self.queue) 18 | self.queue.append(x) 19 | for _ in range(size): 20 | item = self.queue.popleft() 21 | self.queue.append(item) 22 | 23 | def pop(self) -> int: 24 | """ 25 | Removes the element on top of the stack and returns that element. 26 | """ 27 | return self.queue.popleft() 28 | 29 | def top(self) -> int: 30 | """ 31 | Get the top element. 32 | """ 33 | return self.queue[0] 34 | 35 | def empty(self) -> bool: 36 | """ 37 | Returns whether the stack is empty. 38 | """ 39 | return len(self.queue) == 0 40 | -------------------------------------------------------------------------------- /Python/226. InvertBinaryTree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def invertTree(self, root: TreeNode) -> TreeNode: 9 | queue = collections.deque([(root)]) 10 | while queue: 11 | node = queue.popleft() 12 | if node: 13 | node.left, node.right = node.right, node.left 14 | queue.append(node.left) 15 | queue.append(node.right) 16 | return root 17 | -------------------------------------------------------------------------------- /Python/23. MergeKSortedList.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution(object): 7 | def mergeKLists(self, lists): 8 | """ 9 | :type lists: List[ListNode] 10 | :rtype: ListNode 11 | """ 12 | def mergeTwoLists(l1, l2): 13 | curr = dummy = ListNode(0) 14 | while l1 and l2: 15 | if l1.val < l2.val: 16 | curr.next = l1 17 | l1 = l1.next 18 | else: 19 | curr.next = l2 20 | l2 = l2.next 21 | curr = curr.next 22 | curr.next = l1 or l2 23 | return dummy.next 24 | 25 | if not lists: 26 | return None 27 | left, right = 0, len(lists) - 1 28 | while right > 0: 29 | lists[left] = mergeTwoLists(lists[left], lists[right]) 30 | left += 1 31 | right -= 1 32 | if left >= right: 33 | left = 0 34 | return lists[0] 35 | -------------------------------------------------------------------------------- /Python/25. ReverseNodesInK-Group.py: -------------------------------------------------------------------------------- 1 | """ 2 | 25. Reverse Nodes in K-Group 3 | 4 | The program uses a variable(finchk) to check if there are enough(k) nodes remaining to reverse. 5 | If so, it reverses connection(k-1) between each pair of nodes(k) and moves to next group. 6 | If not, it returns the current linked list as answer. 7 | """ 8 | 9 | class Solution: 10 | def reverseKGroup(self, head: ListNode, k: int) -> ListNode: 11 | dummy, dummy.next = ListNode(0), head 12 | prev, cur = dummy, dummy.next 13 | finchk = cur 14 | 15 | while 1: 16 | for _ in range(k): 17 | if not finchk: return dummy.next 18 | finchk = finchk.next 19 | for _ in range(k-1): 20 | cur.next.next, cur.next, prev.next = prev.next, cur.next.next, cur.next 21 | prev, cur = cur, cur.next 22 | return dummy.next 23 | -------------------------------------------------------------------------------- /Python/26. Remove Duplicates from Sorted Array.py: -------------------------------------------------------------------------------- 1 | # Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length. 2 | # 3 | # Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 4 | 5 | 6 | class Solution(object): 7 | def removeDuplicates(self, nums): 8 | """ 9 | :type nums: List[int] 10 | :rtype: int 11 | """ 12 | for i in nums: 13 | if(nums.count(i)>1): 14 | while(nums.count(i)>1): 15 | nums.remove(i) 16 | return len(nums) -------------------------------------------------------------------------------- /Python/263.UglyNumbers.py: -------------------------------------------------------------------------------- 1 | # Having one number num isUgly checks if the only prime divisors of num are 2, 3 and 5. 2 | class Solution(object): 3 | def isUgly(self, num): 4 | if num == 0: 5 | return False 6 | while num % 2 == 0: 7 | num /= 2 8 | while num % 3 == 0: 9 | num /= 3 10 | while num % 5 == 0: 11 | num /= 5 12 | return num == 1 13 | -------------------------------------------------------------------------------- /Python/27. RemoveElement.py: -------------------------------------------------------------------------------- 1 | # Given an array nums and a value val, remove all instances of that value in-place and return the new length. 2 | # Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 3 | # The order of elements can be changed. It doesn't matter what you leave beyond the new length. 4 | 5 | class Solution: 6 | def removeElement(self, nums: List[int], val: int) -> int: 7 | ''' 8 | ignore target element and arrange every other element on starting (n - m) indices, where 9 | n is number of elements in array and m is number of occurrences of target element 10 | ''' 11 | final_index = 0 # to decide indices of elements in final list 12 | items = 0 # modified list's number of values 13 | for index in range(len(nums)): 14 | if nums[index] != val: 15 | nums[index], nums[final_index] = nums[final_index], nums[index] 16 | final_index += 1 17 | items += 1 18 | return items -------------------------------------------------------------------------------- /Python/28. Implement strStr().py: -------------------------------------------------------------------------------- 1 | ''' 2 | 28. Implement strStr() 3 | 4 | Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 5 | If the needle is empty return 0. 6 | ''' 7 | 8 | class Solution: 9 | def strStr(self, haystack: str, needle: str) -> int: 10 | sizeOfNeedle = len(needle) 11 | sizeOfHaystack = len(haystack) 12 | if sizeOfNeedle == 0 or haystack == needle: 13 | return 0 14 | if(sizeOfHaystack < sizeOfNeedle): 15 | return -1 16 | 17 | for i in range(0, sizeOfHaystack): 18 | bound = i + sizeOfNeedle 19 | if bound > sizeOfHaystack: 20 | return -1 21 | 22 | substring = haystack[i:bound] 23 | if substring == needle: 24 | return i 25 | 26 | return -1 -------------------------------------------------------------------------------- /Python/287. FindTheDuplicateNumber.py: -------------------------------------------------------------------------------- 1 | #Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. 2 | #There is only one duplicate number in nums, return this duplicate number. 3 | class Solution(object): 4 | 5 | def findDuplicate(self, nums): 6 | #Traversing the list using for loop 7 | s = sorted(nums) #sorting given array 8 | a,b = 0,len(nums) 9 | temp=(a+b)//2 10 | t = 1 11 | while t: #using binary search to find duplicate 12 | if s[temp] == temp and s[temp-1] == temp: 13 | return s[temp] 14 | if s[temp] == temp+1 and s[temp-1] == temp: 15 | a = temp 16 | else: 17 | b = temp 18 | temp = (a+b)//2 19 | -------------------------------------------------------------------------------- /Python/3. LongestSubstringWithoutRepeatingCharacters.py: -------------------------------------------------------------------------------- 1 | # Given a string s, find the length of the longest substring without repeating characters. 2 | 3 | class Solution(object): 4 | def lengthOfLongestSubstring(self, s): 5 | """ 6 | :type s: str 7 | :rtype: int 8 | """ 9 | start = max_length = 0 10 | used_char = {} 11 | 12 | for i in range(len(s)): 13 | if s[i] in used_char and start <= used_char[s[i]]: 14 | start = used_char[s[i]] + 1 15 | else: 16 | max_length = max(max_length, i - start + 1) 17 | 18 | used_char[s[i]] = i 19 | 20 | return max_length 21 | 22 | sol = Solution() 23 | assert 3 == sol.lengthOfLongestSubstring("abcabcbb") 24 | -------------------------------------------------------------------------------- /Python/338. CountingBits.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: 3 | -------- 4 | 5 | Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num 6 | calculate the number of 1's in their binary representation and return them as an array. 7 | """ 8 | 9 | 10 | from typing import List 11 | 12 | class Solution: 13 | def countBits(self, num: int) -> List[int]: 14 | # Loop from 0 to num, convert them in binary and use 15 | # `count()` to count the occurances of 1. 16 | 17 | result = [bin(i).count('1') for i in range(num + 1)] 18 | return result 19 | -------------------------------------------------------------------------------- /Python/344. ReverseString.py: -------------------------------------------------------------------------------- 1 | #Function to reverse a string 2 | class Solution(object): 3 | def reverseString(self, s): 4 | #Taking variables that point to the starting and end position 5 | i=0 6 | j=len(s) - 1 7 | while(i <= j): 8 | #Swapping the starting and the ending value 9 | s[i] , s[j] = s[j] , s[i] 10 | #Incrementing the variable that points to the starting position and decrementing the variable that points to the last position. 11 | #The loop will continue till the variable pointing the starting value becomes more than the one pointing the ending value. 12 | #This will assure all the characters in the string are swapped. Hence reversing the string 13 | i +=1 14 | j -=1 15 | -------------------------------------------------------------------------------- /Python/347. TopKFrequentElements.py: -------------------------------------------------------------------------------- 1 | # 347. Top K Frequent Elements (https://leetcode.com/problems/top-k-frequent-elements/) 2 | 3 | class Solution(object): 4 | def topKFrequent(self, nums, k): 5 | """ 6 | :type nums: List[int] 7 | :type k: int 8 | :rtype: List[int] 9 | """ 10 | frequencies = {} 11 | for num in nums: 12 | if num in frequencies: 13 | frequencies[num] = frequencies[num] + 1 14 | else: 15 | frequencies[num] = 1 16 | 17 | keys = [] 18 | while len(keys) < k: 19 | maxx = None 20 | keyy = None 21 | for key, value in frequencies.items(): 22 | if not maxx: 23 | keyy = key 24 | maxx = value 25 | continue 26 | if value > maxx: 27 | maxx = value 28 | keyy = key 29 | keys.append(keyy) 30 | frequencies.pop(keyy) 31 | return keys 32 | 33 | -------------------------------------------------------------------------------- /Python/35. SearchInsertPosition.py: -------------------------------------------------------------------------------- 1 | # Given a sorted array of distinct integers and a target value, return the index if the target is found. 2 | # If not, return the index where it would be if it were inserted in order. 3 | 4 | class Solution: 5 | def searchInsert(self, nums: List[int], target: int) -> int: 6 | if target in nums: 7 | return nums.index(target) 8 | else: 9 | for index in range(len(nums)): 10 | if target < nums[index]: 11 | return index 12 | return index + 1 13 | -------------------------------------------------------------------------------- /Python/367.ValidPerfectSquare.py: -------------------------------------------------------------------------------- 1 | #Given a positive integer num, write a function which returns True if num is a perfect square else False. 2 | class Solution(object): 3 | def isPerfectSquare(self, num): 4 | low=0 5 | high=num 6 | #Starting from zero till the number we need to check for perfect square 7 | while(low<=high): 8 | #Calulating middle value by using right shift operator 9 | mid=(low+high)>>1 10 | #If the square of the middle value is equal to the number then it is a perfect square else not 11 | if(mid*mid==num): 12 | return True 13 | #If the square of the middle value is less than the number we increment the low variable else the high variable is decremented. 14 | #The loop will continue till the low value becomes more than the high value or the number is a perfect square then True will be 15 | #returned 16 | elif(mid*mid int: 6 | counts = {} 7 | 8 | # Iterate through array once, adding counts to dictionary 9 | for char in s: 10 | if char in counts: 11 | counts[char] += 1 12 | else: 13 | counts[char] = 1 14 | 15 | # Iterate through array again, finding the first a letter with a count of 0 16 | for index, char in enumerate(s): 17 | if counts[char] == 1: 18 | return index 19 | return -1 -------------------------------------------------------------------------------- /Python/39. combinationSum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: 3 | # This is solved using dynamic programming approach 4 | # Initially we create a dp matrix for elements in target 5 | dp = [[[]]] + [[] for _ in range(target)] 6 | for candidate in candidates: 7 | # Next we iterate for all candidate in canditates and then later iterate from candidate to target+1 8 | for i in range(candidate,target+1): 9 | dp[i] += [sublist + [candidate] for sublist in dp[i-candidate]] 10 | # Here we compute dp using the above method 11 | # This is done by once again iterating over every sublist in the initial list we iterated. 12 | return dp[target] 13 | # Returns answer 14 | -------------------------------------------------------------------------------- /Python/41. firstMissingPositive.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstMissingPositive(self, nums: List[int]) -> int: 3 | # The smallest positive number is 1, hence we set that 4 | smallest = 1 5 | while True: 6 | # We check if this number is present in nums, if it does we add 1 to the number 7 | if smallest in nums: 8 | smallest += 1 9 | else: 10 | # else we just return the previously computed smallest number 11 | return smallest 12 | -------------------------------------------------------------------------------- /Python/441. ArrangingCoins.py: -------------------------------------------------------------------------------- 1 | #Variable n has the number of coins. Two variables row and count are created and assigned to value 0 and 1 respectively. 2 | #Loop continues till the value of variable row is greater than or equal to count as completely filled number of rows is 3 | #required. First we increase the row to 1 as fisrt row should have 1 coin. Then n is decreased by count for calulating 4 | #the remaining number of coins. Then count is incremented by 1 as the next row should have 2 coins. This is continued 5 | #till be find the number of rows completely filled and that value is returned. 6 | class Solution(object): 7 | def arrangeCoins(self, n): 8 | row = 0 9 | count = 1 10 | while(n >= count): 11 | row += 1 12 | n -= count 13 | count += 1 14 | return row 15 | -------------------------------------------------------------------------------- /Python/448.FindAllNumbersDisappearedinanArray.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findDisappearedNumbers(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | ans=list() 8 | for i in range(0,len(nums)): 9 | tmp=abs(nums[i])-1 10 | if nums[tmp]>=0: 11 | nums[tmp]=-nums[tmp] 12 | for i in range(0,len(nums)): 13 | if nums[i]-1>=0: 14 | ans.append(i+1) 15 | return ans 16 | 17 | -------------------------------------------------------------------------------- /Python/455. AssignCookies.py: -------------------------------------------------------------------------------- 1 | # Assume you are an awesome parent and want to give your children some cookies. 2 | # But, you should give each child at most one cookie. 3 | # Each child i has a greed factor g[i], which is the minimum size of a cookie 4 | # that the child will be content with; and each cookie j has a size s[j]. 5 | # If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. 6 | # Your goal is to maximize the number of your content children and output the maximum number. 7 | 8 | 9 | class Solution(object): 10 | def findContentChildren(self, g, s): 11 | """ 12 | :type g: List[int] 13 | :type s: List[int] 14 | :rtype: int 15 | """ 16 | i = 0 17 | j = 0 18 | g = sorted(g) 19 | s = sorted(s) 20 | 21 | while i < len(g) and j < len(s): 22 | if g[i] <= s[j]: 23 | i += 1 24 | j += 1 25 | return i 26 | 27 | -------------------------------------------------------------------------------- /Python/461.HammingDistance.py: -------------------------------------------------------------------------------- 1 | #The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 2 | #we will store the representation in bits of the 2 integers in lists and we'll be comparing element by element 3 | class Solution(object): 4 | def hammingDistance(self, x, y): 5 | a=list(bin(x)[2:]) #bin() transforms an integer into its representation in bits 6 | b=list(bin(y)[2:]) # bin(5) = 0b101 , we'll copy everything starting from third position till the end. that's our number 7 | 8 | # now these next if statements are used to make the lists of equal size because 12 is 1100 and 5 is 101 the number of bits is not equal 9 | 10 | if len(a) > len(b): 11 | b=['0']*(len(a)-len(b))+b 12 | elif len(a) < len(b) : 13 | a= ['0']*(len(b)-len(a))+a 14 | 15 | #continuing from here is easy, we'll just compare element by element and store the number of different bits in d variable 16 | 17 | d=0 18 | for i in range(len(a)): 19 | if a[i] != b[i]: 20 | d+=1 21 | 22 | return d 23 | -------------------------------------------------------------------------------- /Python/485. MaxConsecutiveOnes.py: -------------------------------------------------------------------------------- 1 | #Given a binary array, find the maximum number of consecutive 1s in this array. 2 | #Taking two variables consecutive and result and assigning them to zero. 3 | #Traversing the list if the value 1 is found in the list we add 1 to consecutive. 4 | #If result is less than consecutive then assigning the value of consecutive to result. 5 | #If the consecutive value is also 1 then we increment consecutive by 1 and assign its value to result if value of result is smaller 6 | #If the consecutive value is not 1 then we assingn 0 to consecutive and start over. 7 | #Fianlly the max consecutive value is returned after traversing the list 8 | class Solution(object): 9 | def findMaxConsecutiveOnes(self, nums): 10 | consecutive=0 11 | result=0 12 | for i in nums: 13 | if(i==1): 14 | consecutive += 1 15 | if(result < consecutive): 16 | result = consecutive 17 | else: 18 | consecutive = 0 19 | return result 20 | -------------------------------------------------------------------------------- /Python/5.LongestPalindromicSubstring.py: -------------------------------------------------------------------------------- 1 | #check if string is palindrome or not 2 | def isPalindrome(s, x, y): 3 | while x < y: 4 | if s[x] != s[y]: 5 | return False 6 | x += 1 7 | y -= 1 8 | return True 9 | 10 | def longestPalindrome(s): 11 | n = len(s) 12 | max_ = 0 13 | ans = '' 14 | 15 | if n == 1: 16 | return s 17 | 18 | for i in range(n): 19 | #list of all index which is same as s[i] 20 | duplicate = [j for j in range(i+1, n) if s[j] == s[i]] 21 | 22 | #look through all elements in duplicate if the string is palindrome 23 | for j in duplicate: 24 | #if palinfrome update max value and add sub-string to ans 25 | if isPalindrome(s, i, j) and j - i + 1 > max_: 26 | max_ = j - i + 1 27 | ans = ''.join(s[i:j+1]) 28 | 29 | return ans 30 | 31 | s = 'abacddcliril' 32 | 33 | l = longestPalindrome(list(s)) 34 | 35 | print(l) #liril 36 | -------------------------------------------------------------------------------- /Python/500.KeyboardRow.py: -------------------------------------------------------------------------------- 1 | #Function findWords return list of thoes words from words list that can be typed using only one row from US keyboard. 2 | class Solution(object): 3 | def canUseRow(self, row, word): 4 | return len([x for x in word if x not in row]) == 0 5 | 6 | def isOneRowEnough(self, word): 7 | firstRow = "qwertyuiop" 8 | secondRow = "asdfghjkl" 9 | thirdRow = "zxcvbnm" 10 | word = word.lower() 11 | return self.canUseRow(firstRow, word) or self.canUseRow(secondRow, word) or self.canUseRow(thirdRow, word) 12 | 13 | 14 | def findWords(self, words): 15 | return [x for x in words if self.isOneRowEnough(x)] 16 | -------------------------------------------------------------------------------- /Python/504. Base7.py: -------------------------------------------------------------------------------- 1 | #Function convertToBase7 converts number num to string representing this number in base 7. 2 | class Solution(object): 3 | def convertToBase7(self, num): 4 | if num == 0: 5 | return "0" 6 | digitsList = [] 7 | sign = num//abs(num) 8 | num = abs(num) 9 | while num > 0: 10 | digitsList += [str(num % 7)] 11 | num //= 7 12 | digitsList.reverse() 13 | numberBase7 = "".join(digitsList) 14 | if sign == -1: 15 | return "-" + numberBase7 16 | return numberBase7 -------------------------------------------------------------------------------- /Python/559. MaximumDepthOfN-aryTree.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val=None, children=None): 5 | self.val = val 6 | self.children = children 7 | """ 8 | 9 | class Solution: 10 | # calculate n-ary Tree depth 11 | def maxDepth(self, root: 'Node') -> int: 12 | # if root not exist than return 0 13 | if root == None: 14 | return 0 15 | # if root have't children than return 0 16 | if root.children == None: 17 | return 1 18 | # get max depth in root's children 19 | M = 0 20 | for child in root.children: 21 | M = max(M,self.maxDepth(child)) 22 | # add this root 23 | return M+1 -------------------------------------------------------------------------------- /Python/58. length_of_last_word.py: -------------------------------------------------------------------------------- 1 | ''' 2 | PROBLEM: Length of Last Word 3 | 4 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string. 5 | 6 | If the last word does not exist, return 0. 7 | 8 | Note: A word is defined as a maximal substring consisting of non-space characters only. 9 | 10 | Example: 11 | 12 | Input: "Hello World" 13 | Output: 5 14 | 15 | Problem link : https://leetcode.com/problems/length-of-last-word/ 16 | ''' 17 | 18 | ''' 19 | APPROACH - 20 | We can convert string into list of words and can calculate length using reverse indexing 21 | ''' 22 | 23 | class Solution: 24 | def lengthOfLastWord(self, s: str) -> int: 25 | a = s.split() 26 | if (len(a)>=1): 27 | return len(a[-1]) 28 | else: 29 | return 0 30 | -------------------------------------------------------------------------------- /Python/636. ExclusiveTimeOfFunctions.py: -------------------------------------------------------------------------------- 1 | #636. Exclusive Time of Functions problem is described here : https://leetcode.com/problems/exclusive-time-of-functions/ 2 | 3 | class Solution(object): 4 | def exclusiveTime(self, n, logs): 5 | """ 6 | :type n: int 7 | :type logs: List[str] 8 | :rtype: List[int] 9 | """ 10 | 11 | time = [0 for i in range(n)] 12 | stack = [] 13 | last_timestamp = 0 14 | for log in logs: 15 | parts = log.split(":") 16 | function_id = int(parts[0]) 17 | started = parts[1] == "start" 18 | timestamp = int(parts[2]) 19 | if not started: 20 | timestamp += 1 21 | 22 | if stack: 23 | active_id = stack[-1] 24 | time[active_id] = time[active_id] + (timestamp-last_timestamp) 25 | if started: 26 | stack.append(function_id) 27 | else: 28 | stack.pop() 29 | 30 | last_timestamp = timestamp 31 | 32 | return time 33 | -------------------------------------------------------------------------------- /Python/64. MinPathSum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minPathSum(self, grid: List[List[int]]) -> int: 3 | 4 | m = len(grid) 5 | n = len(grid[0]) 6 | 7 | for i in range(1, n): 8 | grid[0][i] += grid[0][i-1] 9 | 10 | for i in range(1, m): 11 | grid[i][0] += grid[i-1][0] 12 | 13 | for i in range(1, m): 14 | for j in range(1, n): 15 | grid[i][j] += min(grid[i-1][j], grid[i][j-1]) 16 | 17 | return grid[-1][-1] 18 | -------------------------------------------------------------------------------- /Python/647. PalandromicSubstrings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSubstrings(self, s: str) -> int: 3 | n = len(s) 4 | dp = [[0] * n for _ in range(n)] 5 | 6 | res = 0 7 | for i in range(n-1, -1, -1): 8 | for j in range(i, n): 9 | dp[i][j] = s[i] == s[j] and ((j-i+1) < 3 or dp[i+1][j-1]) 10 | res += dp[i][j] 11 | return res 12 | -------------------------------------------------------------------------------- /Python/66. PlusOne.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 66. Plus One 3 | 4 | Given a large integer represented as an integer array, where each element is a digit of the integer. The 5 | digits are ordered from most significant to least significant in left-to-right order. The large integer 6 | does not contain any leading 0's. 7 | Increment the large integer by one and return the resulting array of digits. 8 | ''' 9 | 10 | class Solution: 11 | def plusOne(self, digits: List[int]) -> List[int]: 12 | # Transforming the input array into a list of characters 13 | strs = [str(digit) for digit in digits] 14 | # Joining the characters into a string 15 | string = "".join(strs) 16 | # Transforming the string into an int and adding 1 to it 17 | value = int(string) 18 | value += 1 19 | # Converting the int back to an array and returning 20 | return [int(x) for x in str(value)] -------------------------------------------------------------------------------- /Python/7.ReverseInteger.py: -------------------------------------------------------------------------------- 1 | #This program takes in a number, reverses it and then returns it as the output. 2 | 3 | class Solution(object): 4 | def reverse(self, x): 5 | """ 6 | :type x: int 7 | :rtype: int 8 | """ 9 | 10 | #get positive number irrespestive of the original sign 11 | if x>0: 12 | n = x 13 | else: 14 | n = -x 15 | c = 0 16 | 17 | while n>0: 18 | r = n % 10 19 | c = c*10 + r 20 | n = n // 10 21 | 22 | #reset value to 0 if answer exceeds the constraint 23 | if c>((2**31)-1): 24 | c=0 25 | 26 | #return the answer with the original sign 27 | if x>0: 28 | return c 29 | else: 30 | return -c 31 | -------------------------------------------------------------------------------- /Python/728. SelfDividingNumbers.py: -------------------------------------------------------------------------------- 1 | #Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible. 2 | class Solution: 3 | def selfDividingNumbers(self, left: int, right: int) -> List[int]: 4 | #initialize an empty list 5 | self_dividing_nos = [] 6 | #check for all the numbers in given range if they are self dividing 7 | for num in range(left, right + 1): 8 | num_original = num 9 | while (num > 0): 10 | digit = num % 10 11 | if digit != 0: 12 | if (num_original % digit == 0): 13 | num = num // 10 14 | else: 15 | break 16 | else: 17 | break 18 | if num == 0: 19 | self_dividing_nos.append(num_original) 20 | return self_dividing_nos 21 | 22 | 23 | -------------------------------------------------------------------------------- /Python/73. SetMatrixZeroes.py: -------------------------------------------------------------------------------- 1 | #Given an m x n matrix. If an element is 0, set its entire row and column to 0 2 | #Below is a Constant-space solution of the problem 3 | #Time complexity-O(mn) Space complexity-O(m+n) 4 | 5 | 6 | class Solution: 7 | def setZeroes(self, matrix: List[List[int]]) -> None: 8 | m,n = len(matrix) , len(matrix[0]) 9 | 10 | for i in range(m): #using nested for loops 11 | for j in range(n): 12 | if matrix[i][j] == 0: #if the current cell val is 0 we update the first val of that row or col 13 | matrix[i][0] = 0 14 | matrix[0][j] = 0 15 | 16 | for i in range(m): 17 | for j in range(n): 18 | if matrix[i][0] == 0 or matrix[0][j]== 0: #here we check either the first row or first col of that cell is 0 19 | matrix[i][j] = 0 # if so, we update the value 20 | 21 | -------------------------------------------------------------------------------- /Python/766. ToeplitzMatrix.py: -------------------------------------------------------------------------------- 1 | #A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. 2 | #Now given an M x N matrix, return True if and only if the matrix is Toeplitz. 3 | 4 | class Solution: 5 | def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: 6 | c = True 7 | rows = len(matrix) 8 | cols = len(matrix[0]) 9 | 10 | for x in range(rows): 11 | for y in range(cols): 12 | if x != 0 and y != 0: 13 | if matrix[x][y] != matrix[x-1][y-1]: 14 | c = False 15 | break 16 | if c == False: 17 | return False 18 | else: 19 | return True 20 | -------------------------------------------------------------------------------- /Python/767. ReorganizeString.py: -------------------------------------------------------------------------------- 1 | #767. Reorganize String problem is described here : https://leetcode.com/problems/reorganize-string/ 2 | 3 | class Solution: 4 | def reorganizeString(self, S: str) -> str: 5 | reorg = [None] * len(S) 6 | letters = [[S.count(c), c] for c in set(S)] 7 | letters.sort(reverse=True) 8 | 9 | i = 0 10 | for count, c in letters: 11 | while count: 12 | reorg[i] = c 13 | i += 2 14 | if i >= len(S): 15 | i = 1 16 | count -= 1 17 | for i in range(len(reorg) - 1): 18 | if reorg[i] == reorg[i + 1]: 19 | return "" 20 | return "".join(reorg) 21 | -------------------------------------------------------------------------------- /Python/771. Jewels and Stone.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You're given strings J representing the types of stones that are jewels, and S representing the stones you have. 3 | Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. 4 | 5 | The letters in J are should be distinct, and all characters in J and S are letters. 6 | Letters are case sensitive, so "a" is considered a different type of stone from "A". 7 | ''' 8 | class Solution(object): 9 | def numJewelsInStones(self, J, S): 10 | jewels = {} 11 | for i in J: 12 | jewels[i] = 1 13 | number = 0 14 | for i in S: 15 | if i in jewels: 16 | number+=1 17 | return number 18 | j=input("Enter Jewels: ") 19 | s=input("Enter Stones: ") 20 | ob1 = Solution() 21 | print(ob1.numJewelsInStones(j,s)) -------------------------------------------------------------------------------- /Python/8.PalindromeChecker.py: -------------------------------------------------------------------------------- 1 | #Statement: This program takes a string as input, checks whether the string is a palindrome or not and returns, 2 | # True if yes and returns False if no. 3 | 4 | # For example: "AABBCCBBAA" is a palindrome, so True will be returned. 5 | # "122333221" is again a palindrome, so True will be returned. 6 | # But, "I am a good code" is not a palindrome, so False will be returned. 7 | 8 | class Solution(object): 9 | def palindromeChecker(self, str): 10 | """ 11 | :type str: string 12 | :rtype: boolean 13 | """ 14 | strLower = str.lower() # converts the string into lower case 15 | strList = strLower.split("") # converting the string into a list 16 | strReverse = strList.reverse() # reversing the list 17 | finalStr = "".join(strReverse) # getting the final reversed string 18 | 19 | if finalStr == str: # This part checks if the final reversed string is eqaul to the original string or not. 20 | return True 21 | 22 | else: 23 | return False 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Python/9.Palindrome Number.py: -------------------------------------------------------------------------------- 1 | #This program returns true if the number is a palindrome, else it returns false 2 | 3 | class Solution(object): 4 | def isPalindrome(self, x): 5 | """ 6 | :type x: int 7 | :rtype: bool 8 | """ 9 | #All negative numbers reutrn false for Palindrome 10 | if x < 0: 11 | return False 12 | 13 | a = x 14 | sum = 0 15 | while a > 0 : 16 | r = a % 10 17 | sum = sum*10 + r 18 | a = a // 10 19 | #If reversed number is same as orignal, returns True 20 | if sum==x: 21 | return True 22 | 23 | #else returns false 24 | else: 25 | return False 26 | -------------------------------------------------------------------------------- /Python/905.SortArrayByParity.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortArrayByParity(self, A: List[int]) -> List[int]: 3 | even=0 4 | odd=len(A)-1 5 | 6 | while even int: 8 | output=[] 9 | self.inorder(root,output) 10 | sum=L+R 11 | for i in range(len(output)): 12 | if output[i]>L and output[i] A[i+1]: 18 | i += 1 19 | 20 | return i == N-1 21 | -------------------------------------------------------------------------------- /Python/977.SquaresOfASortedArray.py: -------------------------------------------------------------------------------- 1 | # Having sorted array A of negative and positive integers, sortedSquares 2 | # returns sorted array of squared elements from A 3 | # 4 | # Example: 5 | # A = [-4, -1, 3, 5] 6 | # result = [1, 9, 16, 25] 7 | # 8 | class Solution: 9 | def sortedSquares(self, array: List[int]) -> List[int]: 10 | squared_array = [x*x for x in array] 11 | sorted_array = [] 12 | 13 | left = 0 14 | right = len(squared_array) - 1 15 | 16 | while left <= right: 17 | left_item = squared_array[left] 18 | right_item = squared_array[right] 19 | 20 | if left_item > right_item: 21 | sorted_array.append(left_item) 22 | left += 1 23 | continue 24 | 25 | sorted_array.append(right_item) 26 | right -= 1 27 | 28 | return list(reversed(sorted_array)) 29 | -------------------------------------------------------------------------------- /SQL/175. CombineTwoTables.sql: -------------------------------------------------------------------------------- 1 | # The query selects Names and joins the Address table to the Person table 2 | select p.Firstname, p.LastName, a.City, a.State from Person p left join Address a on p.PersonId = a.PersonId; 3 | -------------------------------------------------------------------------------- /SQL/176. SecondHighestSalary.sql: -------------------------------------------------------------------------------- 1 | /* Solution to Problem 176. Second Highest Salary 2 | 3 | Link to Problem: https://leetcode.com/problems/second-highest-salary/ 4 | 5 | Question: Write a SQL query to get the second highest salary from the Employee table. 6 | 7 | Solution Logic: 8 | 9 | A sub query is first used to select the max salary from the Employee table. 10 | 11 | Considering all other salaries in the table 12 | except the max salary obtained in the subquery, 13 | we then take the max salary from these remaining salaries, 14 | which becomes the second highest salary. 15 | 16 | A subquery was used to select the max salary, since group functions can't be used in WHERE clause. 17 | */ 18 | select max(Salary) SecondHighestSalary from Employee /* Selecting max salary from remaining salaries, renaming the column as SecondHighestSalary */ 19 | where Salary != (select max(Salary) from Employee); /* WHERE clause used to reject only the highest salary in the table. */ -------------------------------------------------------------------------------- /SQL/180. ConsectiveNumbers.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | # Logic - Joined all the three tables using self join and used DISTINCT to removed duplicates. 3 | # Alias Named all the three logs tables as l1, l2, l3 respectively. 4 | 5 | SELECT DISTINCT l1.Num AS ConsecutiveNums 6 | FROM Logs l1, Logs l2, Logs l3 7 | WHERE l1.Id = l2.Id - 1 AND l2.Id = l3.Id - 1 AND l1.Num = l2.Num AND l2.Num = l3.Num; 8 | 9 | -------------------------------------------------------------------------------- /SQL/181. EmployeesEarningMoreThanTheirManagers.sql: -------------------------------------------------------------------------------- 1 | Select a.Name as Employee /* Selecting Column and renaming it */ 2 | from Employee as a join employee as b /* Join with self by using different names */ 3 | on a.ManagerId=b.Id /* Join condition */ 4 | and a.Salary>b.Salary; /* Condition for record selection from joined table */ 5 | -------------------------------------------------------------------------------- /SQL/182. DuplicateEmails.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Since we need to filter all the Emails which has appeared more than once, we can use the count function which is an aggregate function thus, we 3 | use Group by. 4 | Finally, we display Emails whose count is greater than 1. 5 | */ 6 | 7 | select Email from Person group by Email having count(Email)>1; -------------------------------------------------------------------------------- /SQL/183. CustomersWhoNeverOrder.sql: -------------------------------------------------------------------------------- 1 | # We want to select all Customers who never ordered 2 | # Therefor we select them 3 | # and then join onto the orders. 4 | # Afterwards we take out all who have an orderId associated. 5 | select Name as 'Customers' from Customers c left join Orders o on o.CustomerId = c.Id where o.Id is null; -------------------------------------------------------------------------------- /SQL/196. DeleteDuplicateEmails.sql: -------------------------------------------------------------------------------- 1 | # We want to delete duplicate entries and keep the one with the smallest Id 2 | # Therefor we start with a delete query but instead of only doing 3 | # delete from Person 4 | # we go ahead and enter person twice (after the from) 5 | # now we specify which person to delete (e.g. delete p from Person p, Person q) 6 | # and last but not least we filter Person p with having the same email as q and a gerater ID 7 | 8 | delete p from Person p, Person q where p.Email = q.Email and p.Id > q.Id; -------------------------------------------------------------------------------- /SQL/595. Big Countries.sql: -------------------------------------------------------------------------------- 1 | /*There is a table World. 2 | A country is big if it has an area of bigger than 3 million square km or a population of more than 25 million. 3 | 4 | Write a SQL solution to output big countries' name, population and area.*/ 5 | select name,population,area 6 | from World 7 | where area>3000000 OR population>25000000 8 | -------------------------------------------------------------------------------- /SQL/601. HumanTrafficOfStadium.sql: -------------------------------------------------------------------------------- 1 | SELECT wankhede.* FROM stadium wankhede /* Selecting Column and renaming it */ 2 | LEFT JOIN stadium p1 ON wankhede.id - 1 = p1.id /* join conditions */ 3 | LEFT JOIN stadium p2 ON wankhede.id - 2 = p2.id 4 | LEFT JOIN stadium n1 ON wankhede.id + 1 = n1.id 5 | LEFT JOIN stadium n2 ON wankhede.id + 2 = n2.id 6 | WHERE (wankhede.people >= 100 AND p1.people >= 100 AND p2.people >= 100) /* checking necessary conditions */ 7 | OR (wankhede.people >= 100 AND n1.people >= 100 AND n2.people >= 100) 8 | OR (wankhede.people >= 100 AND n1.people >= 100 AND p1.people >= 100) 9 | ORDER BY id; /* ordering the result */ 10 | -------------------------------------------------------------------------------- /SQL/601. Human_Traffic_of_Stadium.sql: -------------------------------------------------------------------------------- 1 | # SQL query to display the records with three or more rows with consecutive id's, and the number of people is greater than or equal to 100 for each. 2 | # Returned table is ordered by visit_date in ascending Order 3 | 4 | select id, visit_date,people from (select 5 | * 6 | ,lead(id,1) over(order by visit_date asc) as id1 7 | ,lead(id,2) over(order by visit_date asc) as id2 8 | ,lag(id,1) over(order by visit_date asc) as id3 9 | ,lag(id,2) over(order by visit_date asc) as id4 10 | from stadium 11 | where people>=100) a where 12 | (id1-id =1 and id2-id1=1) 13 | or (id-id3 =1 and id3-id4=1) 14 | or (id-id3 =1 and id1-id=1) 15 | or (id-id3 =1 and id1-id=1) 16 | -------------------------------------------------------------------------------- /SQL/626. ExchangeSeats.sql: -------------------------------------------------------------------------------- 1 | #This code gives back every entry from the "seat"-Table but switches the ids in pairs (e.g. 1 <-> 2, 3 <-> 4, ...). The last one (if without a partner) stays itself. 2 | 3 | select 4 | (case 5 | when mod(id, 2) != 0 and id = counts then id 6 | when mod(id, 2) != 0 and id != counts then id+1 7 | else id - 1 8 | end) as id, 9 | student 10 | from 11 | seat, 12 | (select 13 | count(*) as counts 14 | from 15 | seat) 16 | as seatCount 17 | order by 18 | id asc; -------------------------------------------------------------------------------- /SQL/627. SwapSalary.sql: -------------------------------------------------------------------------------- 1 | # We want to swap the sex-column in the salary table 2 | # Therefor we do an update-query on the salary table and set the sex-column. 3 | # Now we enter the case-block, which looks at the sex-value for each altered row. 4 | # if it matches 'm' we will set it to 'f'. otherwise it will be set to 'm'. 5 | 6 | update salary set sex = case sex when 'm' then 'f' else 'm' end; -------------------------------------------------------------------------------- /SQL/628. AvgFemSalGreThanMaleSal.sql: -------------------------------------------------------------------------------- 1 | 2 | /* SQL Program to retrieve the department numbers which have female average salary 3 | greater than male average salary of the same department.*/ 4 | 5 | select dno as Dept_No /* Selecting department number */ 6 | from Employee as E1 7 | where E1.gen = 'F' /* Selecting female employees */ 8 | group by dno 9 | having avg(salary) > (select avg(salary) 10 | from Employee as E2 11 | where E2.gen = 'M' /* Selecting male employees */ 12 | and E2.dno = E1.dno) 13 | --------------------------------------------------------------------------------