├── Arrays ├── Array-Nesting-565.java ├── Best-Time-to-Buy-and-Sell-Stock-II.cpp ├── Boats_to_save_people.cpp ├── CanPlaceFlowers605.cpp ├── CanPlaceFlowers605.java ├── Convert-Array-into-Zig-Zag-Fashion.cpp ├── CountNumberOfTeams1395.cpp ├── CountNumberOfTeams1395.java ├── CountPairsWithAbsouteDifferenceK2006.cpp ├── CountPairsWithAbsouteDifferenceK2006.java ├── CountPairsWithGivenSum.cpp ├── CountSpecialQuadruplets1995.cpp ├── CountSpecialQuadruplets1995.java ├── CyclicallyRotateArrayByOne.cpp ├── CyclicallyRotateArrayByOne.java ├── FindAllDuplicatesInAnArray442.cpp ├── FindAllDuplicatesInAnArray442.java ├── FindAllNumbersDisappearedInAnArray448.cpp ├── FindAllNumbersDisappearedInAnArray448.java ├── FindMissingAndRepeatingElements.cpp ├── FindMissingAndRepeatingElements.java ├── FindTwoMissingNumbers.cpp ├── First-Missing-Positive-41.cpp ├── FirstRepeatingElement.cpp ├── GlobalAndLocalInversions775.cpp ├── GlobalAndLocalInversions775.java ├── IncreasingTripletSubsequence334.cpp ├── IncreasingTripletSubsequence334.java ├── Insert-Interval-57.cpp ├── JumpGame3-1306.cpp ├── LongestContinuousIncreasingSubsequence674.cpp ├── LongestContinuousIncreasingSubsequence674.java ├── MaxChunksToMakeSorted769.cpp ├── MaxChunksToMakeSorted769.java ├── MaxConsecutiveOnes485.cpp ├── MaxConsecutiveOnes485.java ├── Maximum-Area-of-a-Piece-of-Cake-After-Horizontal-and-Vertical Cuts-1465.CPP ├── MaximumProductOfTwoElementsInAnArray1464.cpp ├── MaximumProductOfTwoElementsInAnArray1464.java ├── MaximumProductof3Numbers628.cpp ├── MaximumProductof3Numbers628.java ├── MinimumCostsHomecomingOfRobo2087.cpp ├── MinimumCostsHomecomingOfRobo2087.java ├── MinimumMovesToEqualArrayElements453.cpp ├── MinimumMovesToEqualArrayElements453.java ├── MinimumMovestoEqualArrayElementsII472.cpp ├── MinimumMovestoEqualArrayElementsII472.java ├── MinimumNumerOfOperationsToMakeArrayContinuous2009.cpp ├── MinimumNumerOfOperationsToMakeArrayContinuous2009.java ├── MissingNumber268.cpp ├── MissingNumber268.java ├── Move-all-negative-elements-to-the-end.cpp ├── Move_zeroes.py ├── Non-Repeating-Element.cpp ├── Prefix-Sum │ ├── JumpGame7-1871.cpp │ ├── JumpGame7-1871.java │ ├── MaximumNumberOfNonOverlappingSubarraysWithSumEqualsTarget1546.cpp │ ├── MaximumNumberOfNonOverlappingSubarraysWithSumEqualsTarget1546.java │ ├── MinimumOperationsToReduceXToZero1658.cpp │ ├── MinimumOperationsToReduceXToZero1658.java │ ├── MinimumValueToGetPositiveStepByStepSum1413.cpp │ ├── MinimumValueToGetPositiveStepByStepSum1413.java │ ├── ProductOfARrayExceptSelf238.cpp │ ├── ProductOfArrayExceptSelf238.java │ ├── RangeSumQueryImmutable303.cpp │ ├── RangeSumQueryImmutable303.java │ ├── SubarraySumEqualsK560.cpp │ ├── SubarraySumEqualsK560.java │ ├── SubarrayWithGivenXOR.cpp │ ├── SubarrayWithGivenXOR.java │ ├── XORQueriesOfASubarray1310.cpp │ └── XORQueriesOfASubarray1310.java ├── Remove-Duplicates-from-Sorted-Array-2-80.cpp ├── Remove-Duplicates-from-Sorted-Array-26.cpp ├── Remove-Duplicates-from-Sorted-Array-26.java ├── RemovingMinimumNumberofMagicBeans2171.cpp ├── RemovingMinimumNumberofMagicBeans2171.java ├── ReplaceElementsWithGreaterElementOnRightSide1299.cpp ├── ReplaceElementsWithGreaterElementOnRightSide1299.java ├── SingleNumber136.cpp ├── SingleNumber136.java ├── SingleNumber136.py ├── Two-Sum.py ├── TwoSum1.cpp ├── TwoSum1.java ├── Union-of-Arrays.cpp ├── contains-duplicate.cpp ├── find-pivot-index.cpp ├── intersection-of-2-arrays-II.cpp ├── intersection-of-2-arrays.cpp ├── maximum-product-subarray.cpp ├── plus-one.cpp ├── remove_duplicates.cpp ├── rotate-array.cpp ├── rotate-image.cpp ├── subarray-product-less-than-k.cpp └── subarray-sum-equals-k.cpp ├── Backtracking ├── Combination-Sum-2-40.cpp ├── Combination-Sum-2-40.java ├── Combination-Sum-39.cpp ├── Combination-Sum-39.java ├── Combination-Sum-III-216.cpp ├── Combination-Sum-III-216.java ├── Combinations77.cpp ├── Combinations77.java ├── ExpressionAddOperators282.cpp ├── ExpressionAddOperators282.java ├── Generate-Parentheses-22.cpp ├── Letter-Combinations-of-a-Phone-Number-17.cpp ├── LetterCasePermutation784.cpp ├── LetterCasePermutation784.java ├── M-Coloring-Problem.cpp ├── N-Queens-2-52-brute.cpp ├── N-Queens-51-Efficient.cpp ├── N-Queens-51-brute.cpp ├── PalindromePartitioning131.cpp ├── PalindromePartitioning131.java ├── Path-with-Maximum-Gold-1219.cpp ├── Permutation-Sequence-60.cpp ├── Permutations-II-47.cpp ├── Permutations-II-47.java ├── Permutations46.cpp ├── Permutations46.java ├── Rat-in-a-maze.cpp ├── Rat-in-a-maze.java ├── Restore-IP-Addresses-93.cpp ├── Subset-Sum.cpp ├── Subset-Sum.java ├── Subsets-78.cpp ├── Subsets-78.java ├── Subsets-II-90.cpp ├── Subsets-II-90.java ├── Sudoku-Solver-37.cpp ├── Sudoku-Solver-37.java ├── UniquePaths3-980.cpp ├── UniquePaths3-980.java ├── Word-Search-79.cpp └── Word-Search-79.java ├── Binary-Search ├── AggressiveCows.cpp ├── AllocateMinimumNumberOfPages.cpp ├── AllocateMinimumNumberOfPages.java ├── ArrangingCoins441.cpp ├── ArrangingCoins441.java ├── BinarySearch704.cpp ├── BinarySearch704.java ├── CapacityToShipPackagesWithinDDays1011.cpp ├── CapacityToShipPackagesWithinDDays1011.java ├── DivideChocolate1231.cpp ├── DivideChocolate1231.java ├── Find-First-And-Last-Position-of-Element-in-Sorted-Array-34.cpp ├── Find-Minimum-in-Rotated-Sorted-Array-153.cpp ├── Find-Minimum-in-Rotated-Sorted-Array-2-154.cpp ├── Find-Peak-Element-162.cpp ├── Find-Peak-Element-162.java ├── FindSmallestLetterGreaterThanTarget744.cpp ├── FindSmallestLetterGreaterThanTarget744.java ├── FindTheSmallestDivisorGivenAThreshold1283.cpp ├── FindTheSmallestDivisorGivenAThreshold1283.java ├── First-Bad-Version-278.cpp ├── GuessNumberHigherOrLower374.cpp ├── GuessNumberHigherOrLower374.java ├── H-Index-2-275.cpp ├── H-Index-2-275.java ├── H-Index-274.cpp ├── H-Index-274.java ├── KokoEatingBananas875.cpp ├── KokoEatingBananas875.java ├── Kth-Smallest-Element-in-a-sorted-matrix-378.cpp ├── KthElementOfTwoSortedArrays.cpp ├── KthElementOfTwoSortedArrays.java ├── KthMissingPositiveNumber1539.cpp ├── KthMissingPositiveNumber1539.java ├── KthSmallestNumberInMultiplicationTable668.cpp ├── KthSmallestNumberInMultiplicationTable668.java ├── Median-in-a-row-wise-sorted-matrix.cpp ├── Median-in-a-row-wise-sorted-matrix.java ├── Median-of-2-sorted-arrays-4.cpp ├── Median-of-2-sorted-arrays-4.java ├── MinimumNumberOfDaysToMakeMBouquets1482.cpp ├── MinimumNumberOfDaysToMakeMBouquets1482.java ├── Nth-Root-Of-A-Number.cpp ├── NthMagicalNumber878.cpp ├── NthMagicalNumber878.java ├── Search-Insert-Position-35.cpp ├── Search-Insert-Position-35.java ├── Search-a-2D-Matrix-2-240.cpp ├── Search-in-Rotated-Sorted-Array-2-81.cpp ├── Search-in-Rotated-Sorted-Array-33.cpp ├── Search-in-Rotated-Sorted-Array-33.java ├── Search-in-a-2D-Matrix-2-240.java ├── Search-in-a-2D-Matrix-74.cpp ├── Search-in-a-2D-Matrix-74.java ├── SingleElementInASortedArray540.cpp ├── SingleElementInASortedArray540.java ├── SumOfSquareNumbers633.cpp ├── SumOfSquareNumbers633.java ├── ValidPerfectSquare367.cpp └── ValidPerfectSquare367.java ├── Bit-Manipulation ├── Calculate-square-without-using-pow.cpp ├── CalculateSquareWithoutUsingOperators.cpp ├── CalculateSquareWithoutUsingOperators.java ├── ConvertANumberToHexadecimal405.cpp ├── ConvertANumberToHexadecimal405.java ├── Copy-Set-Bits-in-Range.cpp ├── Count-number-of-Bits-to-be-Flipped-to-Convert-A-to-B.cpp ├── CountTotalSetBits.cpp ├── CountTotalSetBits.java ├── Counting-Bits-338.cpp ├── Counting-Bits-338.java ├── Divide-Two-Integers-29.cpp ├── DivideTwoIntegers29.cpp ├── DivideTwoIntegers29.java ├── FIndMSB.java ├── Find-Position-of-Set-Bit.cpp ├── FindMSB.cpp ├── HammingDistance461.cpp ├── HammingDistance461.java ├── Non-Repeating-Numbers.cpp ├── Number-of-1-bits.cpp ├── NumberComplement476.cpp ├── NumberComplement476.java ├── NumberOf1Bits191.cpp ├── NumberOf1Bits191.java ├── NumberOfValidWordsForEAchPuzzle1178.cpp ├── NumberOfValidWordsForEAchPuzzle1178.java ├── Power-Set.cpp ├── Power-Set.java ├── Power-of-Two-231.cpp ├── Power-of-Two-231.java ├── ReverseBits190.cpp ├── ReverseBits190.java ├── SingleNumber136.cpp ├── SingleNumber136.java ├── SingleNumber2-137.cpp ├── SingleNumber2-137.java ├── SingleNumber3-260.cpp ├── SingleNumber3-260.java ├── SingleNumberWithEachElementHavingCountOf3.cpp ├── SingleNumberWithEachElementHavingCountOf3.java └── gray-code.py ├── DP-On-Trees ├── AllPossibleFullBinaryTrees894.cpp ├── AllPossibleFullBinaryTrees894.java ├── Binary-Tree-Maximum-Path-Sum-124.cpp ├── Diameter-Of-Binary-Tree-543.java ├── Diameter-of-a-Binary-Tree-543.cpp ├── Path-Sum-112.cpp ├── Path-Sum-2-113.cpp └── Path-Sum-3-437.cpp ├── Design ├── DesignHashMap706.cpp ├── DesignHashMap706.java ├── Find-Median-From-Data-Stream-295.cpp ├── FlattenNestedListIterator341.cpp ├── FlattenNestedListIterator341.java ├── InsertDeleteGetRandomO(1)380.cpp ├── InsertDeleteGetRandomO(1)380.java ├── IteratorForCombination1286.cpp ├── IteratorForCombination1286.java ├── LFU-Cache-460-DLL.cpp ├── LRU-Cache-146.cpp └── LRU-Cache-146.java ├── Dynamic Programming ├── 0-1 Knapsack │ ├── 0-1-Knapsack.cpp │ ├── Last-Stone-Weight-2-1049-Minimum-Subset-Difference.cpp │ └── LastStoneWeight2-1049.java ├── 3D-DP │ ├── OutOfBoundaryPaths576.cpp │ └── OutOfBoundaryPaths576.java ├── Best-Time-To-Buy-And-Sell-Stock-2-122.java ├── Best-Time-to-Buy-and-Sell-Stock-2-122.cpp ├── Best-Time-to-Buy-and-Sell-Stock-3-123.cpp ├── BestTimeToBuyAndSellStockWithTransactionFee714.cpp ├── BestTimeToBuyAndSellStockWithTransactionFee714.java ├── Bursting-Balloons-312.cpp ├── ChampagneTower799.cpp ├── ChampagneTower799.java ├── CherryPickup741.cpp ├── ClimbingStairs70.cpp ├── ClimbingStairs70.java ├── Coin-Change-2-518.cpp ├── Coin-Change-2-518.java ├── CombinationSum4-377.cpp ├── CombinationSum4-377.java ├── Count-Palindromic-Subsequences.cpp ├── DP or Greedy :? │ ├── MaximumEarningsFromTaxi2008.cpp │ └── MaximumEarningsFromTaxi2008.java ├── DPonStocks │ ├── BestTimeToBuyAndSellStockWithCooldown.cpp │ └── BestTimeToBuyAndSellStockWithTransactionFee.cpp ├── Decode-Ways-91.cpp ├── Delete-Operation-for-Two-Strings-583.cpp ├── DifferentWaysToAddParentheses241.cpp ├── DifferentWaysToAddParentheses241.java ├── Distinct-Subsequences-115.cpp ├── Dungeon-Game-174.cpp ├── Dungeon-Game-174.java ├── Edit-Distance-72.cpp ├── Egg-Drop-with-2-Eggs-and-N-Floors-1884.cpp ├── Fibonacci │ ├── FibonacciNumber509.cpp │ ├── FibonacciNumber509.java │ ├── LengthOfLongestFibonacciSubsequence873.cpp │ ├── LengthOfLongestFibonacciSubsequence873.java │ ├── NthTribonacciNumber1137.cpp │ └── NthTribonacciNumber1137.java ├── Friends-Pairing-Problem.cpp ├── FrogJump403.cpp ├── FrogJump403.java ├── Gold-Mine.cpp ├── House-Robber-198.cpp ├── House-Robber-198.java ├── House-Robber-2-213.cpp ├── House-Robber-2-213.java ├── House-Robber-3-337.cpp ├── House-Robber-3-337.java ├── Interleaving-Strings-97.cpp ├── Jump-Game-2-45.cpp ├── Jump-Game-55.py ├── JumpGame55.cpp ├── Kadane's Algorithm │ ├── Kadane's-Algorithm.java │ ├── Kadanes-Algorithm.cpp │ ├── MaximumProductSubarray152.cpp │ ├── MaximumProductSubarray152.java │ ├── MaximumSumCircularSubarray918.cpp │ ├── MaximumSumCircularSubarray918.java │ ├── MaximumSumOfTwoNonOverlappingSubarrays1031.cpp │ ├── MaximumSumOfTwoNonOverlappingSubarrays1031.java │ └── maximum-subarray.cpp ├── Knapsack-with-Duplicate-Items.cpp ├── Knight-Probability-in-ChessBoard-688.cpp ├── LCS-of-3-strings.cpp ├── Longest Increasing Subsequence │ ├── LargestDivisibleSubset368.cpp │ ├── LargestDivisibleSubset368.java │ ├── LongestArithmeticSubsequence1027.cpp │ ├── LongestArithmeticSubsequence1027.java │ ├── LongestBitonicSubsequence.cpp │ ├── LongestIncreasingSubsequence.cpp │ ├── LongestStringChain.cpp │ ├── MaximumHeightByStackingCuboids1691.cpp │ ├── MaximumHeightByStackingCuboids1691.java │ ├── MinimumNumberOfRemovalsToMakeMountainArray.cpp │ ├── NumberOfLIS.cpp │ ├── NumberOfLongestIncreasingSubsequence673.cpp │ ├── NumberOfLongestIncreasingSubsequence673.java │ ├── PrintLIS.cpp │ ├── Russian-Doll-Envelopes-354.cpp │ └── TheNumberOfWeakCharactersInTheGame1996.cpp ├── Longest-Common-Subsequence-1143.cpp ├── Longest-Common-Substring.cpp ├── Longest-Increasing-Subsequence-300.cpp ├── Longest-Palindrome-409.cpp ├── Longest-Palindromic-Subsequence-516.cpp ├── Longest-Repeating-Subsequence.cpp ├── Longest-Valid-Parentheses-32.cpp ├── Matrix Qs │ ├── CountSquareSubmatricesWithAllOnes1277.cpp │ ├── CountSquareSubmatricesWithAllOnes1277.java │ ├── MinimumFallingPathSum2-1289.cpp │ └── MinimumFallingPathSum2-1289.java ├── MaximalSquare221.cpp ├── MaximalSquare221.java ├── Maximum-Length-of-Pair-Chain-646.cpp ├── Maximum-Path-Sum-in-Matrix.cpp ├── Maximum-Profit-After-K-Transcations.cpp ├── Maximum-Sum-Increasing-Subsequence.cpp ├── MaximumLengthOfRepeatedSubarray718.cpp ├── MaximumLengthOfRepeatedSubarray718.java ├── MinCostClimbingStairs746.cpp ├── MinCostClimbingStairs746.java ├── Minimum-ASCII-Delete-Sum-for-Two-Strings-712.cpp ├── Minimum-Path-Sum-64.cpp ├── Minimum-Path-Sum-64.java ├── MinimumCostForTickets983.cpp ├── MinimumCostForTickets983.java ├── MinimumFallingPathSum931.cpp ├── MinimumFallingPathSum931.java ├── MinimumNumberOfRefuelingStops871.cpp ├── MinimumNumberOfRefuelingStops871.java ├── OnesAndZeroes474.cpp ├── OnesAndZeroes474.java ├── Paint-Fence.cpp ├── Paint-Fence.java ├── Paint-House.cpp ├── Paint-House.java ├── Palindrome-Partitioning-131.cpp ├── Palindrome-Partitioning-2-132.cpp ├── Palindromic String Questions │ ├── LongestPalindromicSubstring5.cpp │ └── LongestPalindromicSubstring5.java ├── Palindromic-Substrings-647.cpp ├── Partition-Equal-Subset-Sum-416.java ├── PartitionArrayForMaximumSum1043.cpp ├── PartitionArrayForMaximumSum1043.java ├── Pascals-Triangle-118.cpp ├── Pascals-Triangle-118.java ├── Pascals-Triangle-2-119.cpp ├── Pascals-Triangle-2-119.java ├── Perfect-Squares-279.java ├── Perfect-Squares-DP-279.cpp ├── Print-Longest-Common-Subsequence.cpp ├── Reach-a-given-score.cpp ├── Regular-Expression-Matching-10.cpp ├── Rod-Cutting-Problem.cpp ├── Shortest-Common-Supersequence-1092.cpp ├── Super-Egg-Drop-887.cpp ├── Target-Sum-494.cpp ├── Target-Sum-494.java ├── Triangle-120.cpp ├── Triangle-120.java ├── Ugly-Number-2-264.cpp ├── Unbounded Knapsack │ ├── Coin-Change-322.java │ ├── coin-change-322-DP-Table.cpp │ └── coin-change.cpp ├── Uncrossed-Lines-1035.cpp ├── Unique-Binary-Search-Trees-96.cpp ├── Unique-Binary-Search-Trees-96.java ├── Unique-Paths-2-63.cpp ├── Unique-Paths-2-63.java ├── UniquePaths64.cpp ├── UniquePaths64.java ├── Wildcard-Matching-44.cpp ├── Word-Break-139.cpp ├── WordBreak.java ├── best-time-to-buy-and-sell-stock-121.java ├── best-time-to-buy-sell-stock-121.cpp ├── contiguous-subarray-sum.cpp ├── longest-palindromic-substring-5.cpp ├── max-absolute-sum-of-subarray.cpp ├── maximal-area-rectangle.cpp ├── partition-equal-subset-sum-416-memoization.cpp ├── partition-equal-subset-sum-416-tabulardp.cpp ├── partition-to-k-equal-sum-subsets-698.cpp └── trapping-rain-water.cpp ├── Graphs ├── 01-Matrix-542.cpp ├── BFS-Traversal.cpp ├── BFS-Traversal.java ├── BipartiteGraph-BFS.cpp ├── BipartiteGraph-BFS.java ├── BipartiteGraph-DFS.cpp ├── BipartiteGraph-DFS.java ├── Cheapest-Flights-within-K-Stops-787.cpp ├── CloneGraph133.cpp ├── CloneGraph133.java ├── Commutable-Islands.cpp ├── Course-Schedule-2-Topological-Sort.cpp ├── Critical-Connections-in-a-Network-1192.cpp ├── DFS-Topological-Sort.cpp ├── DFS-Traversal.cpp ├── DFS-Traversal.java ├── Detect-Cycle-in-Directed-Graph-BFS.cpp ├── Detect-Cycle-in-Directed-Graph-BFS.java ├── Detect-Cycle-in-Directed-Graph-DFS.cpp ├── Detect-Cycle-in-Directed-Graph-DFS.java ├── Detect-Cycle-in-Undirected-Graph_BFS.cpp ├── Detect-Cycle-in-Undirected-Graph_DFS.cpp ├── EvaluateDivision399.cpp ├── EvaluateDivision399.java ├── Flood-Fill-733.cpp ├── Flood-Fill-733.java ├── Is-Graph-Bipartite-785.cpp ├── Kahns-Algo-Topological-Sort-BFS&Queue.cpp ├── MaxAreaOfIsland695.cpp ├── MaxAreaOfIsland695.java ├── Min-Cost-to-Connect-All-Points-1584.cpp ├── Minimum-Steps-By-Knight-1197-BFS.cpp ├── MinimumHeightTrees310.cpp ├── MinimumHeightTrees310.java ├── Network-Delay-Time-Dijkstra+MInHeap-743.cpp ├── NetworkDelayTime743.cpp ├── NetworkDelayTime743.java ├── Number-of-Provinces-547-DFS.cpp ├── Number-of-Provinces-Union-Find-547.cpp ├── NumberofOperationstoMakeNetworkConnected1319.cpp ├── NumberofOperationstoMakeNetworkConnected1319.java ├── Possible-Bipartition.cpp ├── Prims-Minimum-Spanning-Tree.cpp ├── Reconstruct-Itinerary-332.cpp ├── RottingOranges994.cpp ├── RottingOranges994.java ├── Surrounded-Regions-130.cpp ├── Time-Needed-to-Inform-Employees-1376.cpp ├── Word-Ladder-2-126-BFS&DFS.cpp ├── Word-Ladder-BFS-127.cpp ├── course-schedule_GraphColoring_DeadlockDetection.cpp └── number-of-islands.cpp ├── Greedy-Algo ├── ActivitySelection.cpp ├── ActivitySelection.java ├── Cutting-Boards-HackerRank.cpp ├── Find-Minimum-Number-of_fibonacci-Numbers-Whose-Sum-is-K-1414.cpp ├── Fractional-Knapsack.cpp ├── Fractional-Knapsack.java ├── Gas-Station-134.cpp ├── JobSequencingProblem.cpp ├── JobSequencingProblem.java ├── Jump-Game-2-45.cpp ├── Maximize-Toys.cpp ├── Merge Overlapping Questions.txt ├── MinimumNumberOfArrowsToBurstBalloons452.cpp ├── MinimumPlatforms.cpp ├── MinimumPlatforms.java ├── N-Meetings-In-One-Room.cpp ├── N-Meetings-In-One-Room.java ├── NonOverlappingIntervals435.cpp ├── NonOverlappingIntervals435.java ├── Task-Scheduler-621.cpp └── container-with-most-water.cpp ├── Hashing ├── 4Sum-2-454.cpp ├── 4Sum-2-454.java ├── ArrayOfDoubledPairs954.cpp ├── ArrayOfDoubledPairs954.java ├── CountSpecialQuadruplets1995.cpp ├── DistantBarcodes1054.cpp ├── DistantBarcodes1054.java ├── Employee-Importance-690.cpp ├── FindOriginalArrayFromDoubledArray2007.cpp ├── FindOriginalArrayFromDoubledArray2007.java ├── Group-Anagrams-49.cpp ├── IntegerToRoman12.cpp ├── IntegerToRoman12.java ├── Isomorphic-Strings-205.cpp ├── LargestSubarrayWithZeroSum.cpp ├── LargestSubarrayWithZeroSum.java ├── LongestConsecutiveSequence128.cpp ├── LongestConsecutiveSequence128.java ├── RomanToInteger13.cpp ├── RomanToInteger13.java ├── SumOfBeautyOfAllSubstrings1781.cpp ├── SumOfBeautyOfAllSubstrings1781.java ├── longest-substring-without-repeating-characters.cpp └── subarray-sum-divisible-by-k.cpp ├── Heap ├── Connect-Ropes-to-Minimise-Cost.cpp ├── Convert-Min_heap-to-Max-Heap.cpp ├── Find-K-Closest-Elements-658.cpp ├── IPO502.CPP ├── IPO502.java ├── K-Closest-Points-to-Origin-973.cpp ├── Kth-Largest-Element-in-Array-215.cpp ├── Kth-Largest-Element-in-Array-215.java ├── Kth-Largest-Element-in-Stream-703.cpp ├── Kth-Largest-Element-in-Stream-703.java ├── Kth-Smallest-Element-in-a-sorted-matrix-378.cpp ├── Last-Stone-Weight-1046.cpp ├── Last-Stone-Weight-1046.java ├── Maximum-Number-of-Events-that-can-be-attended-1353.cpp ├── MinimumNumberOfRefuelingStops871.cpp ├── MinimumNumberOfRefuelingStops871.java ├── Remove-Stones-to-Minimize-Total-1962.cpp ├── Reorganize-String-767.cpp ├── Sliding-Window-Median-480.cpp ├── Sort-Characters-by-Frequency-451.cpp ├── Sort-Characters-by-Frequency-451.java ├── Third-Maximum-Number-414.cpp ├── Top-K-Frequent-Elements-347.cpp └── Top-K-Frequent-Words-692.cpp ├── InterviewBit └── Arrays │ └── Max-Distance.cpp ├── LICENSE ├── Linked-Lists ├── AddTwoNumbers2-445.cpp ├── AddTwoNumbers2-445.java ├── AddTwoNumbers2.cpp ├── AddTwoNumbers2.java ├── CopyListWithRandomPointer138.cpp ├── CopyListWithRandomPointer138.java ├── DeleteNodeInALinkedList237.cpp ├── DeleteNodeInALinkedList237.java ├── Flattening-a-Linked-List.cpp ├── Flattening-a-Linked-List.java ├── InsertionSortList147.cpp ├── InsertionSortList147.java ├── Intersection-of-Two-Linked-Lists-160.cpp ├── Intersection-of-Two-Linked-Lists-160.java ├── Linked-List-Cycle-141.cpp ├── Linked-List-Cycle-141.java ├── Linked-List-Cycle-2-142.cpp ├── Linked-List-Cycle-2-142.java ├── Merge-K-sorted_lists-23.cpp ├── MergeTwoSortedLists21.cpp ├── MergeTwoSortedLists21.java ├── Middle-Of-The-Linked-List-876.java ├── Middle-Of-the-Linked-List-876 copy.cpp ├── OddEvenLinkedList328.cpp ├── OddEvenLinkedList328.java ├── PalindromicLinkedList234.cpp ├── PalindromicLinkedList234.java ├── Partition-List-86.cpp ├── Remove-Duplicates-From-an-Unsorted-Linked-List.cpp ├── Remove-Duplicates-from-Sorted-List-2-82.cpp ├── Remove-Duplicates-from-Sorted-List-83.cpp ├── Remove-Loop-in-Linked-List.cpp ├── Remove-Nth-Node-From-End-of-List-19.cpp ├── RemoveLinkedListElements203.cpp ├── RemoveLinkedListElements203.java ├── ReorderList143.cpp ├── ReorderList143.java ├── Reverse-Linked-List-in-Groups-of-K.cpp ├── Reverse-Nodes-in-K-Group-25.cpp ├── ReverseLinkedList2-92.cpp ├── ReverseLinkedList2-92.java ├── Rotate-List-61.cpp ├── Rotate-List-61.java ├── Sort-List-148.cpp ├── Swap-Nodes-in-Pairs-24.cpp ├── Swapping-Nodes-in-a-Linked-List-1721.cpp ├── reverse-linked-list-206.cpp └── reverse-linked-list-206.java ├── Math ├── 2KeysKeyboard650.cpp ├── 2KeysKeyboard650.java ├── CountGoodNumbers1922.cpp ├── CountGoodNumbers1922.java ├── ExcelSheetColumnNumber.cpp ├── ExcelSheetColumnTitle.cpp ├── FactorialTrailingZeroes172.cpp ├── FactorialTrailingZeroes172.java ├── FindTheWinnerOfTheCircularGame1823.cpp ├── FindTheWinnerOfTheCircularGame1823.java ├── MonotoneIncreasingDigits738.cpp ├── MonotoneIncreasingDigits738.java ├── Number Theory │ ├── CountPrimes204.cpp │ └── CountPrimes204.java ├── PalindromeNumber9.cpp ├── PalindromeNumber9.java ├── Permutation-Sequence-60.cpp ├── Permutation-Sequence-60.java ├── Power-of-3.cpp ├── Powx-N-50.cpp ├── Powx-N-50.java ├── fizz-buzz.py ├── perfect-squares.py └── ugly-number.cpp ├── Matrix ├── ColoringABorder1034.cpp ├── CountNegativeNumbersInASortedMatrix1351.cpp ├── CountNegativeNumbersInASortedMatrix1351.java ├── CountServersThatCommunicate1267.cpp ├── CountServersThatCommunicate1267.java ├── Determine-whether-matrix-can-be-obtained-by-rotation-1886.cpp ├── Diagonal-Traverse-498.cpp ├── IslandPerimeter463.cpp ├── IslandPerimeter463.java ├── Rotate-Image-48.cpp ├── Rotate-Image-48.java ├── Row-with-max-1s.cpp ├── Search-a-2D-Matrix-74.cpp ├── Set-Matrix-Zeroes-73.cpp ├── Set-Matrix-Zeroes-73.java ├── Spiral-Matrix-2-59.cpp ├── Spiral-Matrix-54.cpp ├── ValidSudoku36.cpp └── ValidSudoku36.java ├── Object-Oriented Design ├── AssignmentOperatorOverloading.cpp ├── DesignParkingSystem1603.cpp ├── DesignParkingSystem1603.java ├── DesignTwitter355.cpp ├── DesignTwitter355.java └── Singleton.java ├── Queues ├── ImplementQueueUsingArray.cpp ├── ImplementQueueUsingArray.java ├── ImplementQueueUsingStacks.cpp ├── ImplementQueueUsingStacks.java ├── ImplementStackUsingQueues.cpp └── ImplementStackUsingQueues.java ├── README.md ├── Searching-Sorting ├── CountInversions.cpp ├── CountInversions.java ├── Majority-Element-169.cpp ├── Majority-Element-169.java ├── Majority-Element-2-229.cpp ├── Majority-Element-2-229.java ├── Merge-Intervals-56.cpp ├── Merge-Intervals-56.java ├── ReversePairs493.cpp ├── ReversePairs493.java ├── Sort-Colors-75.cpp ├── SortAnArray912-QuickSort.cpp ├── SortAnArray912-QuickSort.java ├── find-k-closest-elements.py ├── merge-sorted-arrays-88.cpp └── merge-sorted-arrays-88.java ├── Segment Trees ├── RangeSumQueryMutable-307.cpp └── RangeSumQueryMutable-307.java ├── Sliding-Window ├── BinarySubarraysWithSum930.cpp ├── BinarySubarraysWithSum930.java ├── ContainsDuplicate2-219.cpp ├── ContainsDuplicate2-219.java ├── ContiguousArray525.cpp ├── ContiguousArray525.java ├── CountDistinctInEachWindow.cpp ├── CountDistinctInEachWindow.java ├── CountNumberOfNiceSubarrays1248.cpp ├── CountNumberOfNiceSubarrays1248.java ├── Find-All-Anagrams-in-a-String-438.cpp ├── First-Negative-Integer-in-Every-Window-of-size-K.cpp ├── FruitIntoBaskets904.cpp ├── Longest-K-Unique-Characters-Substring.cpp ├── Longest-Substring-Without-Repeating-Characters-3.cpp ├── Longest-Substring-Without-Repeating-Characters-3.java ├── Longest-Substring-with-at-least-K-Repeating-Characters-395.cpp ├── LongestRepeatingCharacterReplacement424.cpp ├── LongestRepeatingCharacterReplacement424.java ├── LongestSubstringWithAtMostKDistinctCharacters.cpp ├── LongestSubstringWithAtMostKDistinctCharacters.java ├── LongestSubstringWithAtMostTwoDistinctCharacters.cpp ├── LongestSubstringWithAtMostTwoDistinctCharacters.java ├── MaxConsecutiveOnes3-1004.cpp ├── MaxConsecutiveOnes3-1004.java ├── MaximizeTheConfusionOfAnExam2024.cpp ├── MaximizeTheConfusionOfAnExam2024.java ├── MaximumPointsYouCanObtainFromCards1423.cpp ├── MaximumPointsYouCanObtainFromCards1423.java ├── Minimize-the-Heights-1.cpp ├── Minimize-the-Heights-2.cpp ├── Minimum-Size-Subarray-Sum-209.cpp ├── Minimum-Size-Subarray-Sum-209.java ├── Minimum-Window-Substring-76.cpp ├── Number-of-Substrings-Containing-all-3-Characters-1358.cpp ├── Permutation-in-String-567.cpp ├── Permutation-in-String-567.java ├── ReplaceTheSubstringForBalancedString1234.cpp ├── ReplaceTheSubstringForBalancedString1234.java ├── SUbarrayWithKDifferentIntegers992.cpp ├── SUbarrayWithKDifferentIntegers992.java ├── Shortest-Subarray-with-Sum-atleast-K-862.cpp ├── SlidingWindowMaximum239.cpp ├── SlidingWindowMaximum239.java ├── Smallest-Subarray-with-Sum-Greater-than-K.cpp ├── SubarrayProductLessThanK713.cpp └── SubarrayProductLessThanK713.java ├── Stacks ├── 132Pattern456.cpp ├── 132Pattern456.java ├── DailyTemperatures739.cpp ├── DailyTemperatures739.java ├── Decode-String-394.cpp ├── Decode-String-394.java ├── EvaluateReversePolishNotation150.cpp ├── Implement-Queue-Using-Stack-.cpp ├── Implement-Stacks-using-Queue.cpp ├── ImplementStackUsingArray.cpp ├── ImplementStackUsingArray.java ├── Largest-Rectangle-in-Histogram-84.cpp ├── Largest-Rectangle-in-Histogram-84.java ├── Longest-Valid-Parentheses-32.cpp ├── Maximal-Rectangle-85.cpp ├── Min-Stack.cpp ├── Min-Stack.java ├── MinimumAddToMakeParenthesesValid921.cpp ├── MinimumAddToMakeParenthesesValid921.java ├── MinimumNumberOfSwapsToMakeStringBalanced1963.cpp ├── MinimumNumberOfSwapsToMakeStringBalanced1963.java ├── MinimumRemoveToMakeValidParentheses1249.cpp ├── MinimumRemoveToMakeValidParentheses1249.java ├── Monotonic Stack Problems ├── Nearest-Smaller-Element-to-the-Left.cpp ├── NearestSmallerElementToLeft.cpp ├── NearestSmallerElementToLeft.java ├── Next-Greater-Element-1-496.cpp ├── Next-Greater-Element-1-496.java ├── Next-Greater-Element-2-503.cpp ├── Next-Greater-Element-2-503.java ├── Next-Greater-Element-to-the-Right.cpp ├── NextGreaterNodeInLinkedList.cpp ├── NextGreaterNodeInLinkedList.java ├── NumberOfVisiblePeopleInAQueue1944.cpp ├── NumberOfVisiblePeopleInAQueue1944.java ├── OnlineStockSpan901.cpp ├── OnlineStockSpan901.java ├── RemoveKDigits402.cpp ├── RemoveKDigits402.java ├── ScoreOfParentheses856.cpp ├── ScoreOfParentheses856.java ├── Stock-Span-Problem.cpp ├── SumOfSubarrayMinimums907.cpp ├── SumOfSubarrayMinimums907.java ├── Valid-Parentheses-20.cpp └── Valid-Parentheses-20.java ├── Strings ├── BackSpaceStringCompare844.cpp ├── BackSpaceStringCompare844.java ├── ConsecutiveCharacters1446.cpp ├── ConsecutiveCharacters1446.java ├── Count-And-Say-38.cpp ├── Count-And-Say-38.java ├── DetectCapital520.cpp ├── DetectCapital520.java ├── Encode-And-Decode-Strings-271.java ├── ImplementStrStr28.cpp ├── Largest-Number-179.cpp ├── Largest-Number-179.java ├── LengthOfLastWord58.cpp ├── LengthOfLastWord58.java ├── MaximumProductOfWordLengths318.cpp ├── MaximumProductOfWordLengths318.java ├── Next-Greater-Element-3-556.cpp ├── PartitionLabels763.cpp ├── PartitionLabels763.java ├── RansomNote383.cpp ├── RansomNote383.java ├── Remove-Duplicate-Letters-316.cpp ├── ReverseWordsInAString3-557.cpp ├── ReverseWordsInAString3-557.java ├── RotateString796.cpp ├── RotateString796.java ├── SUbstringsOfSizeThreeWithDistinctCharacters1876.cpp ├── SUbstringsOfSizeThreeWithDistinctCharacters1876.java ├── Slowest-Key-1629.cpp ├── UniqueEmailAddresses929.java ├── ZigZagConversion6.cpp ├── first-unique-character-in-string.cpp ├── longest-common-prefix.py ├── maximum-repeating-substring.py ├── valid-anagram.cpp └── valid-palindrome.py ├── Trees ├── BSTToMaxHeap.cpp ├── BSTToMinHeap.cpp ├── BalancedBinaryTree110.cpp ├── BalancedBinaryTree110.java ├── Binary-Tree-Level-Order-Traversal-102.cpp ├── Binary-Tree-Level-Order-Traversal-102.java ├── Binary-Tree-Level-Order-Traversal-2-107.cpp ├── Binary-Tree-Maximum-Path-Sum-124.cpp ├── Binary-Tree-ZigZag-Level-Order-Traversal-103.cpp ├── Binary-Tree-ZigZag-Level-Order-Traversal-103.java ├── BinarySearchTreeIterator173.cpp ├── BinarySearchTreeIterator173.java ├── BinarySearchTreeToGreaterSumTree1038.cpp ├── BinarySearchTreeToGreaterSumTree1038.java ├── BinaryTreeInorderTraversal94.cpp ├── BinaryTreeInorderTraversal94.java ├── BinaryTreePostorderTraversal145.cpp ├── BinaryTreePostorderTraversal145.java ├── BinaryTreePreorderTraversal144.cpp ├── BinaryTreePreorderTraversal144.java ├── BinaryTreePruning814.cpp ├── BinaryTreePruning814.java ├── Bottom-View-of-Binary-Tree.cpp ├── Ceil-in-BST.cpp ├── Ceil-in-BST.java ├── Check-Completeness-of-a-Binary_tree-958.cpp ├── Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal-106.cpp ├── Construct-Binary-Tree-from-Inorder-and-Preorder-Traversal-105.cpp ├── Convert-Sorted-Array-to-Binary-Search-Tree-108.cpp ├── ConvertBSTtoGreaterTree538.cpp ├── ConvertBSTtoGreaterTree538.java ├── ConvertSortedListToBinarySearchTree109.cpp ├── ConvertSortedListToBinarySearchTree109.java ├── Count-Complete-Tree-Nodes-222.cpp ├── Cousins-in-Binary-Tree-993.cpp ├── DeepestLeavesSum1302.cpp ├── DeepestLeavesSum1302.java ├── Delete-Node-In-A-BST-450.cpp ├── Delete-Node-In-A-BST.java ├── Diagonal-Traversal-Of-A-Tree.cpp ├── DiameterOfBinaryTree543.cpp ├── DiameterOfBinaryTree543.java ├── Flatten-Binary-Tree-to-Linked-List-114.cpp ├── Flatten-Binary-Tree-to-Linked-List-114.java ├── Floor-In-BST.cpp ├── Floor-In-BST.java ├── HeightOfBinaryTree.cpp ├── HeightOfBinaryTree.java ├── InorderTraversalOfCartesianTree.cpp ├── InorderTraversalOfCartesianTree.java ├── Insert-Into-A-Binary-Search-Tree-701.cpp ├── Insert-Into-A-Binary-Search-Tree-701.java ├── Invert-Binary-Tree-226.cpp ├── Invert-Binary-Tree-226.java ├── KthLargestElementInBST.cpp ├── KthLargestElementInBST.java ├── KthSmallestElementInBST.cpp ├── KthSmallestElementInBST.java ├── LargestBSTInABinaryTree.cpp ├── LargestBSTInABinaryTree.java ├── Left-View-Of-Binary-Tree.java ├── Left-View-of-Binary-Tree.cpp ├── Lowest-Common-Ancestor-of-a-Binary-Search-Tree-235.cpp ├── Lowest-Common-Ancestor-of-a-Binary-Search-Tree-235.java ├── LowestCommonAncestor236.cpp ├── LowestCommonAncestor236.java ├── MaximumLevelSumOfABinaryTree1161.cpp ├── MaximumLevelSumOfABinaryTree1161.java ├── RangeSumOfBST938.cpp ├── RangeSumOfBST938.java ├── RightSideViewOfBinaryTree199.cpp ├── RightSideViewOfBinaryTree199.java ├── Same-Tree-100.cpp ├── Same-Tree-100.java ├── Serialize-And-Deserialize-Binary-Tree-297.cpp ├── Serialize-And-Deserialize-Binary-Tree-297.java ├── SubtreeOfAnotherTree572.cpp ├── SubtreeOfAnotherTree572.java ├── SumOfLeftLeaves404.cpp ├── SumOfLeftLeaves404.java ├── SumRootToLeafBinaryNumbers1022.cpp ├── SumRootToLeafBinaryNumbers1022.java ├── SumRootToLeafNumbers129.cpp ├── SumRootToLeafNumbers129.java ├── TopViewOfBinaryTree.cpp ├── TwoSum4-InputIsABST653.cpp ├── TwoSum4-InputIsABST653.java ├── UniqueBinarySearchTrees2-95.cpp └── UniqueBinarySearchTrees2-95.java ├── Tries ├── Design-Add-and-Search-Words-Data-Structure-211.cpp ├── Implement-Trie-208.cpp └── Word-Search-2-212.cpp ├── Two Pointers ├── 3-Sum-15.cpp ├── 3-Sum-15.java ├── 3Sum-Closest-16.cpp ├── 3Sum-Closest-16.java ├── 4-Sum-18.cpp ├── 4-Sum-18.java ├── ContainerWithMostWater11.cpp ├── ContainerWithMostWater11.java ├── Find-the-Duplicate-Number-287.cpp ├── Find-the-Duplicate-Number-287.java ├── IntersectionOfTwoSortedArrays.cpp ├── IntersectionOfTwoSortedArrays.java ├── IntervalListIntersections986.cpp ├── IntervalListIntersections986.java ├── LongestMountainInArray845.cpp ├── LongestMountainInArray845.java ├── Middle-Of-The-Linked-List-876.java ├── Middle-Of-the-Linked-List-876.cpp ├── MoveZeroes283.cpp ├── MoveZeroes283.java ├── MoveZeroes283.py ├── Remove-Nth-Node-From-End-of-List-19.cpp ├── Remove-Nth-Node-From-End-of-List-19.java ├── RotateArray189.cpp ├── RotateArray189.java ├── SquaresOfASortedArray977.cpp ├── SquaresOfASortedArray977.java ├── Trapping-Rain-Water-42.cpp ├── Trapping-Rain-Water-42.java ├── TwoSum2-InputArrayIsSorted167.cpp ├── TwoSum2-InputArrayIsSorted167.java ├── next-permutation-31.cpp └── next-permutation-31.java ├── Union Find ├── AccountsMerge721.cpp ├── AccountsMerge721.java ├── RedundantConnections684.cpp └── RedundantConnections684.java └── big-o-cheatsheet.pdf /Arrays/Best-Time-to-Buy-and-Sell-Stock-II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int profit = 0; 5 | for(int i=1; i prices[i-1]) 7 | profit += prices[i] - prices[i-1]; 8 | } 9 | return profit; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Arrays/CyclicallyRotateArrayByOne.cpp: -------------------------------------------------------------------------------- 1 | // Given an array, rotate the array by one position in clock-wise direction. 2 | // Example 1: 3 | // Input: 4 | // N = 5 5 | // A[] = {1, 2, 3, 4, 5} 6 | // Output: 7 | // 5 1 2 3 4 8 | // Example 2: 9 | // Input: 10 | // N = 8 11 | // A[] = {9, 8, 7, 6, 4, 2, 1, 3} 12 | // Output: 13 | // 3 9 8 7 6 4 2 1 14 | 15 | // Your Task: 16 | // You don't need to read input or print anything. Your task is to complete the function rotate() which takes the array A[] and its size N as inputs and modify the array. 17 | 18 | // Expected Time Complexity: O(N) 19 | // Expected Auxiliary Space: O(1) 20 | 21 | // Constraints: 22 | // 1<=N<=105 23 | // 0<=a[i]<=105 24 | 25 | void rotate(int arr[], int n) 26 | { 27 | int temp = arr[n-1]; 28 | for(int i = n-2; i >= 0; i--) 29 | arr[i+1] = arr[i]; 30 | arr[0] = temp; 31 | } -------------------------------------------------------------------------------- /Arrays/CyclicallyRotateArrayByOne.java: -------------------------------------------------------------------------------- 1 | // Given an array, rotate the array by one position in clock-wise direction. 2 | // Example 1: 3 | // Input: 4 | // N = 5 5 | // A[] = {1, 2, 3, 4, 5} 6 | // Output: 7 | // 5 1 2 3 4 8 | // Example 2: 9 | // Input: 10 | // N = 8 11 | // A[] = {9, 8, 7, 6, 4, 2, 1, 3} 12 | // Output: 13 | // 3 9 8 7 6 4 2 1 14 | 15 | // Your Task: 16 | // You don't need to read input or print anything. Your task is to complete the function rotate() which takes the array A[] and its size N as inputs and modify the array. 17 | 18 | // Expected Time Complexity: O(N) 19 | // Expected Auxiliary Space: O(1) 20 | 21 | // Constraints: 22 | // 1<=N<=105 23 | // 0<=a[i]<=105 24 | 25 | class Compute { 26 | 27 | public void rotate(int arr[], int n) 28 | { 29 | int temp = arr[n-1]; 30 | for(int i = n-2; i >= 0; i--) 31 | arr[i+1] = arr[i]; 32 | arr[0] = temp; 33 | } 34 | } -------------------------------------------------------------------------------- /Arrays/FindAllDuplicatesInAnArray442.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer array nums of length n where all the integers of nums are in the range 2 | // [1, n] and each integer appears once or twice, return an array of all the integers that 3 | // appears twice. 4 | // You must write an algorithm that runs in O(n) time and uses only constant extra space. 5 | 6 | // Example 1: 7 | // Input: nums = [4,3,2,7,8,2,3,1] 8 | // Output: [2,3] 9 | // Example 2: 10 | // Input: nums = [1,1,2] 11 | // Output: [1] 12 | // Example 3: 13 | // Input: nums = [1] 14 | // Output: [] 15 | 16 | // Constraints: 17 | // n == nums.length 18 | // 1 <= n <= 105 19 | // 1 <= nums[i] <= n 20 | // Each element in nums appears once or twice. 21 | 22 | class Solution { 23 | public: 24 | vector findDuplicates(vector& nums) { 25 | vector res; 26 | for(int n : nums){ 27 | n = abs(n); 28 | if(nums[n - 1] > 0) 29 | nums[n - 1] *= -1; 30 | else res.push_back(n); 31 | } 32 | return res; 33 | } 34 | }; -------------------------------------------------------------------------------- /Arrays/FindAllDuplicatesInAnArray442.java: -------------------------------------------------------------------------------- 1 | // Given an integer array nums of length n where all the integers of nums are in the range 2 | // [1, n] and each integer appears once or twice, return an array of all the integers that 3 | // appears twice. 4 | // You must write an algorithm that runs in O(n) time and uses only constant extra space. 5 | 6 | // Example 1: 7 | // Input: nums = [4,3,2,7,8,2,3,1] 8 | // Output: [2,3] 9 | // Example 2: 10 | // Input: nums = [1,1,2] 11 | // Output: [1] 12 | // Example 3: 13 | // Input: nums = [1] 14 | // Output: [] 15 | 16 | // Constraints: 17 | // n == nums.length 18 | // 1 <= n <= 105 19 | // 1 <= nums[i] <= n 20 | // Each element in nums appears once or twice. 21 | 22 | class Solution { 23 | public List findDuplicates(int[] nums) { 24 | List res = new ArrayList<>(); 25 | for(int n : nums){ 26 | n = Math.abs(n); 27 | if(nums[n-1] > 0) 28 | nums[n-1] *= -1; 29 | else res.add(n); 30 | } 31 | return res; 32 | } 33 | } -------------------------------------------------------------------------------- /Arrays/FindAllNumbersDisappearedInAnArray448.cpp: -------------------------------------------------------------------------------- 1 | // Given an array nums of n integers where nums[i] is in the range [1, n], 2 | // return an array of all the integers in the range [1, n] that do not appear in nums. 3 | 4 | // Example 1: 5 | // Input: nums = [4,3,2,7,8,2,3,1] 6 | // Output: [5,6] 7 | // Example 2: 8 | // Input: nums = [1,1] 9 | // Output: [2] 10 | 11 | // Constraints: 12 | // n == nums.length 13 | // 1 <= n <= 105 14 | // 1 <= nums[i] <= n 15 | 16 | // Follow up: Could you do it without extra space and in O(n) runtime? 17 | // You may assume the returned list does not count as extra space. 18 | 19 | class Solution { 20 | public: 21 | vector findDisappearedNumbers(vector& nums) { 22 | vector ans; 23 | for(int num : nums){ 24 | if(nums[abs(num) - 1] > 0) 25 | nums[abs(num) - 1] *= -1; 26 | } 27 | for(int i = 0; i < nums.size(); i++) 28 | if(nums[i] > 0) 29 | ans.push_back(i+1); 30 | 31 | return ans; 32 | } 33 | }; -------------------------------------------------------------------------------- /Arrays/FindAllNumbersDisappearedInAnArray448.java: -------------------------------------------------------------------------------- 1 | // Given an array nums of n integers where nums[i] is in the range [1, n], 2 | // return an array of all the integers in the range [1, n] that do not appear in nums. 3 | 4 | // Example 1: 5 | // Input: nums = [4,3,2,7,8,2,3,1] 6 | // Output: [5,6] 7 | // Example 2: 8 | // Input: nums = [1,1] 9 | // Output: [2] 10 | 11 | // Constraints: 12 | // n == nums.length 13 | // 1 <= n <= 105 14 | // 1 <= nums[i] <= n 15 | 16 | // Follow up: Could you do it without extra space and in O(n) runtime? 17 | // You may assume the returned list does not count as extra space. 18 | class Solution { 19 | public List findDisappearedNumbers(int[] nums) { 20 | List ans = new ArrayList<>(); 21 | for(int num : nums) 22 | if(nums[Math.abs(num) - 1] > 0) 23 | nums[Math.abs(num) - 1] *= - 1; 24 | for(int i = 0; i < nums.length; i++) 25 | if(nums[i] > 0) 26 | ans.add(i+1); 27 | return ans; 28 | } 29 | } -------------------------------------------------------------------------------- /Arrays/First-Missing-Positive-41.cpp: -------------------------------------------------------------------------------- 1 | // Given an unsorted integer array nums, find the smallest missing positive integer. 2 | 3 | // You must implement an algorithm that runs in O(n) time and uses constant extra space. 4 | 5 | // Example 1: 6 | 7 | // Input: nums = [1,2,0] 8 | // Output: 3 9 | // Example 2: 10 | 11 | // Input: nums = [3,4,-1,1] 12 | // Output: 2 13 | // Example 3: 14 | 15 | // Input: nums = [7,8,9,11,12] 16 | // Output: 1 17 | 18 | // Constraints: 19 | 20 | // 1 <= nums.length <= 5 * 105 21 | // -231 <= nums[i] <= 231 - 1 22 | 23 | class Solution { 24 | public: 25 | int firstMissingPositive(vector& nums) { 26 | int n = nums.size(), i = 0; 27 | while(i < n){ 28 | if(nums[i] > 0 and nums[i] <= n and nums[i] != nums[nums[i] - 1]) 29 | swap(nums[i], nums[nums[i]-1]); 30 | else i++; 31 | } 32 | for(int i=0; i& nums) { 22 | int mini = INT_MAX, secondMini = INT_MAX; 23 | for(int num : nums){ 24 | if(num <= mini) mini = num; 25 | else if(num < secondMini) 26 | secondMini = num; 27 | else if(num > secondMini) return true; 28 | } 29 | return false; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Arrays/IncreasingTripletSubsequence334.java: -------------------------------------------------------------------------------- 1 | // Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that 2 | // i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false. 3 | // Example 1: 4 | // Input: nums = [1,2,3,4,5] 5 | // Output: true 6 | // Explanation: Any triplet where i < j < k is valid. 7 | // Example 2: 8 | // Input: nums = [5,4,3,2,1] 9 | // Output: false 10 | // Explanation: No triplet exists. 11 | // Example 3: 12 | // Input: nums = [2,1,5,0,4,6] 13 | // Output: true 14 | // Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6. 15 | // Constraints: 16 | // 1 <= nums.length <= 5 * 105 17 | // -231 <= nums[i] <= 231 - 1 18 | 19 | class Solution { 20 | public boolean increasingTriplet(int[] nums) { 21 | int mini = Integer.MAX_VALUE, secondMini = Integer.MAX_VALUE; 22 | for(int num : nums){ 23 | if(num <= mini) mini = num; 24 | else if(num < secondMini) secondMini = num; 25 | else if(num > secondMini) return true; 26 | } 27 | return false; 28 | } 29 | } -------------------------------------------------------------------------------- /Arrays/MaxConsecutiveOnes485.cpp: -------------------------------------------------------------------------------- 1 | // Given a binary array nums, return the maximum number of consecutive 1's in the array. 2 | 3 | // Example 1: 4 | // Input: nums = [1,1,0,1,1,1] 5 | // Output: 3 6 | // Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of 7 | // consecutive 1s is 3. 8 | // Example 2: 9 | // Input: nums = [1,0,1,1,0,1] 10 | // Output: 2 11 | 12 | // Constraints: 13 | // 1 <= nums.length <= 105 14 | // nums[i] is either 0 or 1. 15 | 16 | class Solution { 17 | public: 18 | int findMaxConsecutiveOnes(vector& nums) { 19 | int maxi = 0, sum = 0; 20 | for(int num : nums){ 21 | if(num == 0) sum = 0; 22 | else sum += num; 23 | maxi = max(maxi, sum); 24 | } 25 | return maxi; 26 | } 27 | }; -------------------------------------------------------------------------------- /Arrays/MaxConsecutiveOnes485.java: -------------------------------------------------------------------------------- 1 | // Given a binary array nums, return the maximum number of consecutive 1's in the array. 2 | 3 | // Example 1: 4 | // Input: nums = [1,1,0,1,1,1] 5 | // Output: 3 6 | // Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of 7 | // consecutive 1s is 3. 8 | // Example 2: 9 | // Input: nums = [1,0,1,1,0,1] 10 | // Output: 2 11 | 12 | // Constraints: 13 | // 1 <= nums.length <= 105 14 | // nums[i] is either 0 or 1. 15 | 16 | class Solution { 17 | public int findMaxConsecutiveOnes(int[] nums) { 18 | int maxi = 0, sum = 0; 19 | for(int num : nums){ 20 | if(num == 0) sum = 0; 21 | else sum += num; 22 | maxi = Math.max(maxi, sum); 23 | } 24 | return maxi; 25 | } 26 | } -------------------------------------------------------------------------------- /Arrays/MaximumProductOfTwoElementsInAnArray1464.java: -------------------------------------------------------------------------------- 1 | // Given the array of integers nums, you will choose two different indices i and j of that array. 2 | // Return the maximum value of (nums[i]-1)*(nums[j]-1). 3 | 4 | // Example 1: 5 | // Input: nums = [3,4,5,2] 6 | // Output: 12 7 | // Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. 8 | // Example 2: 9 | 10 | // Input: nums = [1,5,4,5] 11 | // Output: 16 12 | // Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16. 13 | // Example 3: 14 | // Input: nums = [3,7] 15 | // Output: 12 16 | 17 | // Constraints: 18 | // 2 <= nums.length <= 500 19 | // 1 <= nums[i] <= 10^3 20 | 21 | class Solution { 22 | public int maxProduct(int[] nums) { 23 | int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE; 24 | for(int num : nums){ 25 | if(num > max1){ 26 | max2 = max1; 27 | max1 = num; 28 | } 29 | else if(num > max2) 30 | max2 = num; 31 | } 32 | return (max1 - 1) * (max2 - 1); 33 | } 34 | } -------------------------------------------------------------------------------- /Arrays/MinimumMovesToEqualArrayElements453.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. 2 | 3 | // In one move, you can increment n - 1 elements of the array by 1. 4 | 5 | 6 | 7 | // Example 1: 8 | 9 | // Input: nums = [1,2,3] 10 | // Output: 3 11 | // Explanation: Only three moves are needed (remember each move increments two elements): 12 | // [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] 13 | // Example 2: 14 | 15 | // Input: nums = [1,1,1] 16 | // Output: 0 17 | 18 | 19 | // Constraints: 20 | 21 | // n == nums.length 22 | // 1 <= nums.length <= 105 23 | // -109 <= nums[i] <= 109 24 | // The answer is guaranteed to fit in a 32-bit integer. 25 | 26 | class Solution { 27 | public: 28 | int minMoves(vector& nums) { 29 | int res = 0, mini = INT_MAX; 30 | for(int num : nums) mini = min(mini, num); 31 | for(int num : nums) res += num - mini; 32 | return res; 33 | } 34 | }; -------------------------------------------------------------------------------- /Arrays/MinimumMovesToEqualArrayElements453.java: -------------------------------------------------------------------------------- 1 | // Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. 2 | 3 | // In one move, you can increment n - 1 elements of the array by 1. 4 | 5 | 6 | 7 | // Example 1: 8 | 9 | // Input: nums = [1,2,3] 10 | // Output: 3 11 | // Explanation: Only three moves are needed (remember each move increments two elements): 12 | // [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] 13 | // Example 2: 14 | 15 | // Input: nums = [1,1,1] 16 | // Output: 0 17 | 18 | 19 | // Constraints: 20 | 21 | // n == nums.length 22 | // 1 <= nums.length <= 105 23 | // -109 <= nums[i] <= 109 24 | // The answer is guaranteed to fit in a 32-bit integer. 25 | 26 | class Solution { 27 | public int minMoves(int[] nums) { 28 | int res= 0, mini = Integer.MAX_VALUE; 29 | for(int num : nums) 30 | mini = Math.min(mini, num); 31 | for(int num : nums) 32 | res += num - mini; 33 | return res; 34 | } 35 | } -------------------------------------------------------------------------------- /Arrays/MinimumMovestoEqualArrayElementsII472.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. 2 | 3 | // In one move, you can increment or decrement an element of the array by 1. 4 | 5 | // Test cases are designed so that the answer will fit in a 32-bit integer. 6 | 7 | 8 | 9 | // Example 1: 10 | 11 | // Input: nums = [1,2,3] 12 | // Output: 2 13 | // Explanation: 14 | // Only two moves are needed (remember each move increments or decrements one element): 15 | // [1,2,3] => [2,2,3] => [2,2,2] 16 | // Example 2: 17 | 18 | // Input: nums = [1,10,2,9] 19 | // Output: 16 20 | 21 | 22 | // Constraints: 23 | 24 | // n == nums.length 25 | // 1 <= nums.length <= 105 26 | // -109 <= nums[i] <= 109 27 | 28 | 29 | class Solution { 30 | public: 31 | int minMoves2(vector& nums) { 32 | int i=0, j = nums.size() - 1, count = 0; 33 | sort(begin(nums), end(nums)); 34 | while(i < j){ 35 | count += nums[j--] - nums[i++]; 36 | } 37 | return count; 38 | } 39 | }; -------------------------------------------------------------------------------- /Arrays/MinimumMovestoEqualArrayElementsII472.java: -------------------------------------------------------------------------------- 1 | // Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. 2 | 3 | // In one move, you can increment or decrement an element of the array by 1. 4 | 5 | // Test cases are designed so that the answer will fit in a 32-bit integer. 6 | 7 | 8 | 9 | // Example 1: 10 | 11 | // Input: nums = [1,2,3] 12 | // Output: 2 13 | // Explanation: 14 | // Only two moves are needed (remember each move increments or decrements one element): 15 | // [1,2,3] => [2,2,3] => [2,2,2] 16 | // Example 2: 17 | 18 | // Input: nums = [1,10,2,9] 19 | // Output: 16 20 | 21 | 22 | // Constraints: 23 | 24 | // n == nums.length 25 | // 1 <= nums.length <= 105 26 | // -109 <= nums[i] <= 109 27 | 28 | class Solution { 29 | public int minMoves2(int[] nums) { 30 | int i = 0, count = 0, j = nums.length - 1; 31 | Arrays.sort(nums); 32 | while(i < j) 33 | count += nums[j--] - nums[i++]; 34 | return count; 35 | } 36 | } -------------------------------------------------------------------------------- /Arrays/Move-all-negative-elements-to-the-end.cpp: -------------------------------------------------------------------------------- 1 | // Given an unsorted array arr[] of size N having both negative and positive integers. 2 | // The task is place all negative element at the end of array without changing the 3 | // order of positive element and negative element. 4 | 5 | // Example 1: 6 | 7 | // Input : 8 | // N = 8 9 | // arr[] = {1, -1, 3, 2, -7, -5, 11, 6 } 10 | // Output : 11 | // 1 3 2 11 6 -1 -7 -5 12 | 13 | // Example 2: 14 | 15 | // Input : 16 | // N=8 17 | // arr[] = {-5, 7, -3, -4, 9, 10, -1, 11} 18 | // Output : 19 | // 7 9 10 11 -5 -3 -4 -1 20 | 21 | // Expected Time Complexity: O(N) 22 | // Expected Auxiliary Space: O(N) 23 | 24 | // Constraints: 25 | // 1 ≤ N ≤ 105 26 | // -105 ≤ arr[] ≤ 105 27 | 28 | class Solution{ 29 | public: 30 | void segregateElements(int arr[],int n) 31 | { 32 | int i = n, j = n-1; 33 | while(i >= 0 and j >= 0){ 34 | if(arr[j] < 0){ 35 | i--; 36 | swap(arr[i], arr[j]); 37 | } 38 | j--; 39 | } 40 | return; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Arrays/Move_zeroes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. 3 | 4 | Note that you must do this in-place without making a copy of the array. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: nums = [0,1,0,3,12] 11 | Output: [1,3,12,0,0] 12 | Example 2: 13 | 14 | Input: nums = [0] 15 | Output: [0] 16 | 17 | 18 | Constraints: 19 | 20 | 1 <= nums.length <= 104 21 | -231 <= nums[i] <= 231 - 1 22 | 23 | 24 | Follow up: Could you minimize the total number of operations done? 25 | """ 26 | 27 | 28 | class Solution: 29 | def moveZeroes(self, nums: List[int]) -> None: 30 | """ 31 | Do not return anything, modify nums in-place instead. 32 | """ 33 | n = len(nums) 34 | j, z = 0, 0 35 | for num in nums: 36 | if num!=0: 37 | nums[j] = num 38 | j+=1 39 | else: z+=1 40 | for i in range(z): 41 | nums[j] = 0 42 | j += 1 43 | return nums 44 | -------------------------------------------------------------------------------- /Arrays/Prefix-Sum/SubarraySumEqualsK560.cpp: -------------------------------------------------------------------------------- 1 | // Given an array of integers nums and an integer k, return the total number of continuous 2 | // subarrays whose sum equals to k. 3 | 4 | // Example 1: 5 | // Input: nums = [1,1,1], k = 2 6 | // Output: 2 7 | // Example 2: 8 | // Input: nums = [1,2,3], k = 3 9 | // Output: 2 10 | 11 | // Constraints: 12 | 13 | // 1 <= nums.length <= 2 * 104 14 | // -1000 <= nums[i] <= 1000 15 | // -107 <= k <= 107 16 | 17 | class Solution { 18 | public: 19 | int subarraySum(vector& nums, int k) { 20 | int count = 0, n = nums.size(), sum = 0; 21 | unordered_map m; 22 | m[0] = 0; 23 | for(int i = 0; i < n; i++){ 24 | sum += nums[i]; 25 | if(sum == k) count++; 26 | if(m.find(sum - k) != m.end()) 27 | count += m[sum - k]; 28 | m[sum]++ ; 29 | } 30 | return count; 31 | } 32 | }; -------------------------------------------------------------------------------- /Arrays/Prefix-Sum/SubarraySumEqualsK560.java: -------------------------------------------------------------------------------- 1 | // Given an array of integers nums and an integer k, return the total number of continuous 2 | // subarrays whose sum equals to k. 3 | 4 | // Example 1: 5 | // Input: nums = [1,1,1], k = 2 6 | // Output: 2 7 | // Example 2: 8 | // Input: nums = [1,2,3], k = 3 9 | // Output: 2 10 | 11 | // Constraints: 12 | 13 | // 1 <= nums.length <= 2 * 104 14 | // -1000 <= nums[i] <= 1000 15 | // -107 <= k <= 107 16 | 17 | class Solution { 18 | public int subarraySum(int[] nums, int k) { 19 | int sum = 0, n = nums.length, count = 0; 20 | Map mp = new HashMap<>(); 21 | mp.put(0, 0); 22 | for(int i = 0; i < n; i++){ 23 | sum += nums[i]; 24 | if(sum == k) count++; 25 | if(mp.containsKey(sum - k)) 26 | count += mp.get(sum - k); 27 | mp.put(sum, mp.getOrDefault(sum, 0) + 1); 28 | } 29 | return count; 30 | } 31 | } -------------------------------------------------------------------------------- /Arrays/SingleNumber136.cpp: -------------------------------------------------------------------------------- 1 | // Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. 2 | 3 | // You must implement a solution with a linear runtime complexity and use only constant extra space. 4 | 5 | 6 | 7 | // Example 1: 8 | 9 | // Input: nums = [2,2,1] 10 | // Output: 1 11 | // Example 2: 12 | 13 | // Input: nums = [4,1,2,1,2] 14 | // Output: 4 15 | // Example 3: 16 | 17 | // Input: nums = [1] 18 | // Output: 1 19 | 20 | 21 | // NOT CONSTANT SPACE 22 | 23 | class Solution { 24 | public: 25 | int singleNumber(vector& nums) { 26 | unordered_map m; 27 | for(auto num:nums){ 28 | m[num]++; 29 | } 30 | for(auto num:nums) 31 | if(m[num]==1) return num; 32 | return -1; 33 | } 34 | }; 35 | 36 | 37 | // CONSTANT SPACE 38 | 39 | class Solution { 40 | public: 41 | int singleNumber(vector& nums) { 42 | int ans = 0; 43 | for(auto a : nums) 44 | ans ^= a; 45 | return ans; 46 | } 47 | }; -------------------------------------------------------------------------------- /Arrays/SingleNumber136.java: -------------------------------------------------------------------------------- 1 | // Given a non-empty array of integers nums, every element appears twice except for one. 2 | // Find that single one. 3 | // You must implement a solution with a linear runtime complexity and use only constant extra space. 4 | 5 | // Example 1: 6 | // Input: nums = [2,2,1] 7 | // Output: 1 8 | // Example 2: 9 | // Input: nums = [4,1,2,1,2] 10 | // Output: 4 11 | // Example 3: 12 | // Input: nums = [1] 13 | // Output: 1 14 | 15 | // Constraints: 16 | // 1 <= nums.length <= 3 * 104 17 | // -3 * 104 <= nums[i] <= 3 * 104 18 | // Each element in the array appears twice except for one element which appears only once. 19 | 20 | class Solution { 21 | public int singleNumber(int[] nums) { 22 | int ans = 0; 23 | for(int num : nums) 24 | ans ^= num; 25 | return ans; 26 | } 27 | } -------------------------------------------------------------------------------- /Arrays/SingleNumber136.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. 3 | 4 | You must implement a solution with a linear runtime complexity and use only constant extra space. 5 | 6 | """ 7 | 8 | from collections import Counter 9 | 10 | class Solution: 11 | def singleNumber(self, nums: List[int]) -> int: 12 | return (2*sum(set(nums))- sum(nums)) 13 | -------------------------------------------------------------------------------- /Arrays/Two-Sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 3 | 4 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 5 | 6 | You can return the answer in any order. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: nums = [2,7,11,15], target = 9 13 | Output: [0,1] 14 | Output: Because nums[0] + nums[1] == 9, we return [0, 1]. 15 | Example 2: 16 | 17 | Input: nums = [3,2,4], target = 6 18 | Output: [1,2] 19 | Example 3: 20 | 21 | Input: nums = [3,3], target = 6 22 | Output: [0,1] 23 | """ 24 | 25 | class Solution: 26 | def twoSum(self, nums: List[int], target: int) -> List[int]: 27 | d = {} 28 | n = len(nums) 29 | for i in range(n): 30 | goal = target - nums[i] 31 | if goal in d: 32 | return [d[goal], i] 33 | d[nums[i]] = i 34 | return -1 35 | -------------------------------------------------------------------------------- /Arrays/TwoSum1.cpp: -------------------------------------------------------------------------------- 1 | // Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 2 | 3 | // You may assume that each input would have exactly one solution, and you may not use the same element 4 | // twice. 5 | // You can return the answer in any order. 6 | 7 | // Example 1: 8 | // Input: nums = [2,7,11,15], target = 9 9 | // Output: [0,1] 10 | // Output: Because nums[0] + nums[1] == 9, we return [0, 1]. 11 | // Example 2: 12 | // Input: nums = [3,2,4], target = 6 13 | // Output: [1,2] 14 | // Example 3: 15 | // Input: nums = [3,3], target = 6 16 | // Output: [0,1] 17 | 18 | // Constraints: 19 | // 2 <= nums.length <= 104 20 | // -109 <= nums[i] <= 109 21 | // -109 <= target <= 109 22 | // Only one valid answer exists. 23 | 24 | class Solution { 25 | public: 26 | vector twoSum(vector& nums, int target) { 27 | unordered_map m; 28 | for(int i = 0; i < nums.size(); i++){ 29 | if(m.count(target - nums[i])) 30 | return {i, m[target-nums[i]]}; 31 | m[nums[i]] = i; 32 | } 33 | return {-1, -1}; 34 | } 35 | }; -------------------------------------------------------------------------------- /Arrays/contains-duplicate.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. 2 | 3 | 4 | 5 | // Example 1: 6 | 7 | // Input: nums = [1,2,3,1] 8 | // Output: true 9 | // Example 2: 10 | 11 | // Input: nums = [1,2,3,4] 12 | // Output: false 13 | // Example 3: 14 | 15 | // Input: nums = [1,1,1,3,3,4,3,2,4,2] 16 | // Output: true 17 | 18 | class Solution { 19 | public: 20 | bool containsDuplicate(vector& nums) { 21 | unordered_map m; 22 | for(auto num:nums) 23 | { m[num]++; 24 | if(m[num] > 1) 25 | return true; 26 | } 27 | return false; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Arrays/remove_duplicates.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. 2 | 3 | // Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. 4 | 5 | // Return k after placing the final result in the first k slots of nums. 6 | 7 | // Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. 8 | 9 | class Solution { 10 | public: 11 | int removeDuplicates(vector& nums) { 12 | if(nums.size()<=1) return nums.size(); 13 | int j=0; 14 | for(int i=1; i& nums, int k) { 33 | int n = nums.size(); 34 | k = k%n; 35 | vectorans; 36 | for(int i=0; i>& A) { 12 | for(int i=0; i& nums, int k) { 19 | if(k<=1) return 0; 20 | int left = 0, right = 0, prod = 1, result = 0; 21 | while(right=k){ 24 | prod /= nums[left]; 25 | left++; 26 | } 27 | result += right-left+1; 28 | right++; 29 | } 30 | return result; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Arrays/subarray-sum-equals-k.cpp: -------------------------------------------------------------------------------- 1 | // Given an array of integers nums and an integer k, 2 | // return the total number of continuous subarrays whose sum equals to k. 3 | 4 | // Example 1: 5 | 6 | // Input: nums = [1,1,1], k = 2 7 | // Output: 2 8 | // Example 2: 9 | 10 | // Input: nums = [1,2,3], k = 3 11 | // Output: 2 12 | 13 | // https://www.youtube.com/watch?v=HbbYPQc-Oo4&t=525s 14 | 15 | class Solution { 16 | public: 17 | // Using the Optimized, single traversal algorithm with O(N) time complexity instead of the O(N*N) approach 18 | int subarraySum(vector& nums, int k) { 19 | int n = nums.size(); 20 | if(n == 0) return 0; 21 | int count = 0, i = 0; 22 | unordered_map m; 23 | int current_sum = 0; 24 | while(i> ans; 29 | void backtrack(int n, int k, int start, vector temp){ 30 | if(temp.size() == k){ 31 | ans.push_back(temp); 32 | return; 33 | } 34 | for(int i = start; i <= n; i++){ 35 | temp.push_back(i); 36 | backtrack(n, k, i + 1, temp); 37 | temp.pop_back(); 38 | } 39 | } 40 | 41 | vector> combine(int n, int k){ 42 | vector temp; 43 | if(n < k) 44 | return ans; 45 | backtrack(n, k, 1, temp); 46 | return ans; 47 | } 48 | }; 49 | 50 | -------------------------------------------------------------------------------- /Backtracking/Combinations77.java: -------------------------------------------------------------------------------- 1 | // Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. 2 | // You may return the answer in any order. 3 | 4 | // Example 1: 5 | // Input: n = 4, k = 2 6 | // Output: 7 | // [ 8 | // [2,4], 9 | // [3,4], 10 | // [2,3], 11 | // [1,2], 12 | // [1,3], 13 | // [1,4], 14 | // ] 15 | // Example 2: 16 | // Input: n = 1, k = 1 17 | // Output: [[1]] 18 | 19 | // Constraints: 20 | // 1 <= n <= 20 21 | // 1 <= k <= n 22 | 23 | class Solution { 24 | 25 | public void backtrack(int n, int k, int start, List temp, List> ans){ 26 | if(k == temp.size()){ 27 | ans.add(new ArrayList(temp)); 28 | return; 29 | } 30 | for(int i = start; i <= n; i++){ 31 | temp.add(i); 32 | backtrack(n, k, i+1, temp, ans); 33 | temp.remove(temp.size()-1); 34 | } 35 | return; 36 | } 37 | public List> combine(int n, int k) { 38 | List> ans = new ArrayList>(); 39 | if(n < k) return ans; 40 | backtrack(n, k, 1, new ArrayList(), ans); 41 | return ans; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Backtracking/Generate-Parentheses-22.cpp: -------------------------------------------------------------------------------- 1 | // Given n pairs of parentheses, write a function to generate 2 | // all combinations of well-formed parentheses. 3 | 4 | // Example 1: 5 | 6 | // Input: n = 3 7 | // Output: ["((()))","(()())","(())()","()(())","()()()"] 8 | // Example 2: 9 | 10 | // Input: n = 1 11 | // Output: ["()"] 12 | 13 | // Constraints: 14 | 15 | // 1 <= n <= 8 16 | 17 | class Solution { 18 | public: 19 | vector generateParenthesis(int n) { 20 | vector output; 21 | backtrack(output, "", 0, 0, n); 22 | return output; 23 | } 24 | 25 | void backtrack(vector &output, string s, int open, int close, int pairs){ 26 | if(s.size() == pairs*2){ 27 | output.push_back(s); 28 | return; 29 | } 30 | if(open < pairs) backtrack(output, s + "(", open+1, close, pairs); 31 | if(close < open) backtrack(output, s + ")", open, close+1, pairs); 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Backtracking/Subsets-II-90.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer array nums that may contain duplicates, return all possible subsets (the power set). 2 | // The solution set must not contain duplicate subsets. Return the solution in any order. 3 | 4 | // Example 1: 5 | 6 | // Input: nums = [1,2,2] 7 | // Output: [[],[1],[1,2],[1,2,2],[2],[2,2]] 8 | // Example 2: 9 | 10 | // Input: nums = [0] 11 | // Output: [[],[0]] 12 | 13 | // Constraints: 14 | 15 | // 1 <= nums.length <= 10 16 | // -10 <= nums[i] <= 10 17 | 18 | class Solution { 19 | public: 20 | void backtrack(vector> &ans, vector &temp, vector &nums, int start){ 21 | ans.push_back(temp); 22 | for(int i=start; i start and nums[i]==nums[i-1]) continue; 24 | temp.push_back(nums[i]); 25 | backtrack(ans, temp, nums, i+1); 26 | temp.pop_back(); 27 | } 28 | } 29 | vector> subsetsWithDup(vector& nums) { 30 | vector> ans; 31 | vector temp; 32 | sort(nums.begin(), nums.end()); 33 | backtrack(ans, temp, nums, 0); 34 | return ans; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Backtracking/Subsets-II-90.java: -------------------------------------------------------------------------------- 1 | // Given an integer array nums that may contain duplicates, return all possible subsets (the power set). 2 | // The solution set must not contain duplicate subsets. Return the solution in any order. 3 | 4 | // Example 1: 5 | 6 | // Input: nums = [1,2,2] 7 | // Output: [[],[1],[1,2],[1,2,2],[2],[2,2]] 8 | // Example 2: 9 | 10 | // Input: nums = [0] 11 | // Output: [[],[0]] 12 | 13 | // Constraints: 14 | 15 | // 1 <= nums.length <= 10 16 | // -10 <= nums[i] <= 10 17 | 18 | 19 | class Solution { 20 | public void backtrack(int[] nums, List temp, int start, List> ans){ 21 | ans.add(new ArrayList<>(temp)); 22 | for(int i = start; i < nums.length; i++){ 23 | if(i > start && nums[i] == nums[i-1]) continue; 24 | temp.add(nums[i]); 25 | backtrack(nums, temp, i+1, ans); 26 | temp.remove(temp.size()-1); 27 | } 28 | return; 29 | } 30 | 31 | public List> subsetsWithDup(int[] nums) { 32 | Arrays.sort(nums); 33 | List> ans = new ArrayList<>(); 34 | backtrack(nums, new ArrayList<>(), 0, ans); 35 | return ans; 36 | } 37 | } -------------------------------------------------------------------------------- /Binary-Search/ArrangingCoins441.cpp: -------------------------------------------------------------------------------- 1 | // You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where 2 | // the ith row has exactly i coins. The last row of the staircase may be incomplete. 3 | // Given the integer n, return the number of complete rows of the staircase you will build. 4 | 5 | // Example 1: 6 | // Input: n = 5 7 | // Output: 2 8 | // Explanation: Because the 3rd row is incomplete, we return 2. 9 | // Example 2: 10 | // Input: n = 8 11 | // Output: 3 12 | // Explanation: Because the 4th row is incomplete, we return 3. 13 | 14 | // Constraints: 15 | // 1 <= n <= 231 - 1 16 | 17 | class Solution { 18 | public: 19 | int arrangeCoins(int n) { 20 | long left = 0, right = n, curr, mid; 21 | while(left <= right){ 22 | mid = left + (right - left) / 2; 23 | curr = (mid * (mid + 1)) / 2; 24 | if(curr == n) 25 | return mid; 26 | else if(curr < n) 27 | left = mid + 1; 28 | else right = mid - 1; 29 | } 30 | return right; 31 | } 32 | }; -------------------------------------------------------------------------------- /Binary-Search/ArrangingCoins441.java: -------------------------------------------------------------------------------- 1 | // You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where 2 | // the ith row has exactly i coins. The last row of the staircase may be incomplete. 3 | // Given the integer n, return the number of complete rows of the staircase you will build. 4 | 5 | // Example 1: 6 | // Input: n = 5 7 | // Output: 2 8 | // Explanation: Because the 3rd row is incomplete, we return 2. 9 | // Example 2: 10 | // Input: n = 8 11 | // Output: 3 12 | // Explanation: Because the 4th row is incomplete, we return 3. 13 | 14 | // Constraints: 15 | // 1 <= n <= 231 - 1 16 | 17 | class Solution { 18 | public int arrangeCoins(int n) { 19 | long curr = 0, mid = 0, left = 0, right = n; 20 | while(left <= right){ 21 | mid = left + (right - left) / 2; 22 | curr = mid * (mid + 1) / 2; 23 | if(curr == n) return (int) mid; 24 | if(curr < n) left = mid + 1; 25 | else right = mid - 1; 26 | } 27 | return (int) right; 28 | } 29 | } -------------------------------------------------------------------------------- /Binary-Search/BinarySearch704.cpp: -------------------------------------------------------------------------------- 1 | // Given an array of integers nums which is sorted in ascending order, and an integer target, 2 | // write a function to search target in nums. If target exists, then return its index. Otherwise, 3 | // return -1. 4 | // You must write an algorithm with O(log n) runtime complexity. 5 | 6 | // Example 1: 7 | // Input: nums = [-1,0,3,5,9,12], target = 9 8 | // Output: 4 9 | // Explanation: 9 exists in nums and its index is 4 10 | // Example 2: 11 | // Input: nums = [-1,0,3,5,9,12], target = 2 12 | // Output: -1// Explanation: 2 does not exist in nums so return -1 13 | 14 | // Constraints: 15 | // 1 <= nums.length <= 104 16 | // -104 < nums[i], target < 104 17 | // All the integers in nums are unique. 18 | // nums is sorted in ascending order. 19 | 20 | class Solution { 21 | public: 22 | int search(vector& nums, int target) { 23 | int left = 0, right = nums.size() - 1, mid = 0; 24 | while(left <= right){ 25 | mid = left + (right - left) / 2; 26 | if(nums[mid] == target) 27 | return mid; 28 | else if(target < nums[mid]) 29 | right = mid - 1; 30 | else left = mid + 1; 31 | } 32 | return -1; 33 | } 34 | }; -------------------------------------------------------------------------------- /Binary-Search/BinarySearch704.java: -------------------------------------------------------------------------------- 1 | // Given an array of integers nums which is sorted in ascending order, and an integer target, 2 | // write a function to search target in nums. If target exists, then return its index. Otherwise, 3 | // return -1. 4 | // You must write an algorithm with O(log n) runtime complexity. 5 | 6 | // Example 1: 7 | // Input: nums = [-1,0,3,5,9,12], target = 9 8 | // Output: 4 9 | // Explanation: 9 exists in nums and its index is 4 10 | // Example 2: 11 | // Input: nums = [-1,0,3,5,9,12], target = 2 12 | // Output: -1// Explanation: 2 does not exist in nums so return -1 13 | 14 | // Constraints: 15 | // 1 <= nums.length <= 104 16 | // -104 < nums[i], target < 104 17 | // All the integers in nums are unique. 18 | // nums is sorted in ascending order. 19 | 20 | class Solution { 21 | public int search(int[] nums, int target) { 22 | int left = 0, right = nums.length - 1, mid = 0; 23 | while(left <= right){ 24 | mid = left + (right - left) / 2; 25 | if(nums[mid] == target) 26 | return mid; 27 | else if(target < nums[mid]) 28 | right = mid - 1; 29 | else left = mid + 1; 30 | } 31 | return -1; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Binary-Search/KthMissingPositiveNumber1539.cpp: -------------------------------------------------------------------------------- 1 | // Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. 2 | // Find the kth positive integer that is missing from this array. 3 | 4 | // Example 1: 5 | // Input: arr = [2,3,4,7,11], k = 5 6 | // Output: 9 7 | // Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9. 8 | // Example 2: 9 | // Input: arr = [1,2,3,4], k = 2 10 | // Output: 6 11 | // Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6. 12 | 13 | // Constraints: 14 | // 1 <= arr.length <= 1000 15 | // 1 <= arr[i] <= 1000 16 | // 1 <= k <= 1000 17 | // arr[i] < arr[j] for 1 <= i < j <= arr.length 18 | 19 | class Solution { 20 | public: 21 | int findKthPositive(vector& arr, int k) { 22 | int low = 0, high = arr.size() - 1, mid = 0; 23 | while(low <= high){ 24 | mid = low + (high - low) / 2; 25 | if(arr[mid] - (mid + 1) < k) 26 | low = mid + 1; 27 | else 28 | high = mid - 1; 29 | } 30 | return low + k; 31 | } 32 | }; -------------------------------------------------------------------------------- /Binary-Search/KthMissingPositiveNumber1539.java: -------------------------------------------------------------------------------- 1 | // Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. 2 | // Find the kth positive integer that is missing from this array. 3 | 4 | // Example 1: 5 | // Input: arr = [2,3,4,7,11], k = 5 6 | // Output: 9 7 | // Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9. 8 | // Example 2: 9 | // Input: arr = [1,2,3,4], k = 2 10 | // Output: 6 11 | // Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6. 12 | 13 | // Constraints: 14 | // 1 <= arr.length <= 1000 15 | // 1 <= arr[i] <= 1000 16 | // 1 <= k <= 1000 17 | // arr[i] < arr[j] for 1 <= i < j <= arr.length 18 | 19 | class Solution { 20 | public int findKthPositive(int[] arr, int k) { 21 | int low = 0, high = arr.length - 1, mid; 22 | while(low <= high){ 23 | mid = low + (high - low) / 2; 24 | if(arr[mid] - (mid + 1) < k) 25 | low = mid + 1; 26 | else high = mid - 1; 27 | } 28 | return low + k; 29 | } 30 | } -------------------------------------------------------------------------------- /Binary-Search/KthSmallestNumberInMultiplicationTable668.cpp: -------------------------------------------------------------------------------- 1 | // Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer 2 | // matrix mat where mat[i][j] == i * j (1-indexed). 3 | // Given three integers m, n, and k, return the kth smallest element in the m x n multiplication table. 4 | 5 | // Example 1: 6 | // Input: m = 3, n = 3, k = 5 7 | // Output: 3 8 | // Explanation: The 5th smallest number is 3. 9 | // Example 2: 10 | // Input: m = 2, n = 3, k = 6 11 | // Output: 6 12 | // Explanation: The 6th smallest number is 6. 13 | 14 | // Constraints: 15 | // 1 <= m, n <= 3 * 104 16 | // 1 <= k <= m * n 17 | 18 | class Solution { 19 | public: 20 | bool countSmallerOrEqualTo(int mid, int m, int n, int k){ 21 | int count = 0; 22 | for(int i = 1; i <= m; i++) 23 | count += min(n, mid / i); 24 | return count >= k; 25 | } 26 | int findKthNumber(int m, int n, int k) { 27 | int low = 1, high = m*n; 28 | while(low <= high){ 29 | int mid = low + (high - low) / 2; 30 | if(!countSmallerOrEqualTo(mid, m, n, k)) 31 | low = mid + 1; 32 | else high = mid - 1; 33 | } 34 | return low; 35 | } 36 | }; -------------------------------------------------------------------------------- /Binary-Search/Nth-Root-Of-A-Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find nth root of a number m upto p decimal places. 3 | */ 4 | 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | // multiply num n times 10 | double multiply(double num, int n) { 11 | double ans = 1.0; 12 | while(n--) 13 | ans *= num; 14 | 15 | return ans; 16 | } 17 | 18 | void getNthRoot(int n, int m, int p) { 19 | double start = 1, end = m; 20 | double eps = pow(10, -p); 21 | 22 | while((end - start) > eps) { 23 | double mid = start + (end - start) / 2; 24 | if(multiply(mid, n) < m) 25 | start = mid; 26 | else 27 | end = mid; 28 | } 29 | 30 | cout << "estimated ans:"; 31 | cout << start << " " << end << endl; 32 | cout << "actual ans:"; 33 | cout << pow(m, (double)(1.0 / (double)n)); 34 | } 35 | 36 | int main() { 37 | 38 | int n, m, p; 39 | cin >> n >> m >> p; 40 | 41 | getNthRoot(n, m, p); 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /Binary-Search/NthMagicalNumber878.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devangi2000/Data-Structures-Algorithms-Handbook/127615e814dc3a53e25e01be86fadab458050ec0/Binary-Search/NthMagicalNumber878.cpp -------------------------------------------------------------------------------- /Binary-Search/SumOfSquareNumbers633.cpp: -------------------------------------------------------------------------------- 1 | // Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c. 2 | 3 | // Example 1: 4 | // Input: c = 5 5 | // Output: true 6 | // Explanation: 1 * 1 + 2 * 2 = 5 7 | // Example 2: 8 | // Input: c = 3 9 | // Output: false 10 | // Example 3: 11 | // Input: c = 4 12 | // Output: true 13 | // Example 4: 14 | // Input: c = 2 15 | // Output: true 16 | // Example 5: 17 | // Input: c = 1 18 | // Output: true 19 | 20 | // Constraints: 21 | // 0 <= c <= 231 - 1 22 | 23 | class Solution { 24 | public: 25 | bool judgeSquareSum(int c) { 26 | if(c < 0) return false; 27 | long int low = 0, high = sqrt(c); 28 | while(low <= high){ 29 | long int curr = (low * low) + (high * high); 30 | if(curr < c) 31 | low++; 32 | else if(curr > c) 33 | high--; 34 | else return true; 35 | } 36 | return false; 37 | } 38 | }; -------------------------------------------------------------------------------- /Binary-Search/SumOfSquareNumbers633.java: -------------------------------------------------------------------------------- 1 | // Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c. 2 | 3 | // Example 1: 4 | // Input: c = 5 5 | // Output: true 6 | // Explanation: 1 * 1 + 2 * 2 = 5 7 | // Example 2: 8 | // Input: c = 3 9 | // Output: false 10 | // Example 3: 11 | // Input: c = 4 12 | // Output: true 13 | // Example 4: 14 | // Input: c = 2 15 | // Output: true 16 | // Example 5: 17 | // Input: c = 1 18 | // Output: true 19 | 20 | // Constraints: 21 | // 0 <= c <= 231 - 1 22 | 23 | class Solution { 24 | public boolean judgeSquareSum(int c) { 25 | if(c < 0) return false; 26 | long low = 0, high = (long)Math.sqrt(c); 27 | while(low <= high){ 28 | long curr = (low * low) + (high * high); 29 | if(curr < c) 30 | low++; 31 | else if(curr > c) 32 | high--; 33 | else return true; 34 | } 35 | return false; 36 | } 37 | } -------------------------------------------------------------------------------- /Binary-Search/ValidPerfectSquare367.cpp: -------------------------------------------------------------------------------- 1 | // Given a positive integer num, write a function which returns True if num is a perfect square else False. 2 | // Follow up: Do not use any built-in library function such as sqrt. 3 | 4 | // Example 1: 5 | 6 | // Input: num = 16 7 | // Output: true 8 | // Example 2: 9 | 10 | // Input: num = 14 11 | // Output: false 12 | 13 | // Constraints: 14 | // 1 <= num <= 2^31 - 1 15 | 16 | // METHOD 1 : LOL 17 | class Solution { 18 | public: 19 | bool isPerfectSquare(int num){ 20 | return float(sqrt(num)) == int(sqrt(num)); 21 | } 22 | }; 23 | 24 | // DO THIS IN AN INTERVIEW 25 | class Solution { 26 | public: 27 | bool isPerfectSquare(int num){ 28 | int low = 1, high = num; 29 | 30 | while(low <= high){ 31 | long mid = low + (high - low) / 2; 32 | if(mid * mid == num) 33 | return true; 34 | else if(mid*mid > num) 35 | high = mid - 1; 36 | else low = mid + 1; 37 | } 38 | return false; 39 | } 40 | }; -------------------------------------------------------------------------------- /Binary-Search/ValidPerfectSquare367.java: -------------------------------------------------------------------------------- 1 | // Given a positive integer num, write a function which returns True if num is a perfect square else False. 2 | // Follow up: Do not use any built-in library function such as sqrt. 3 | 4 | // Example 1: 5 | 6 | // Input: num = 16 7 | // Output: true 8 | // Example 2: 9 | 10 | // Input: num = 14 11 | // Output: false 12 | 13 | // Constraints: 14 | // 1 <= num <= 2^31 - 1 15 | 16 | class Solution { 17 | public boolean isPerfectSquare(int num) { 18 | int left = 1, right = num; 19 | while(left <= right){ 20 | long mid = left + (right - left) / 2; 21 | if(mid*mid == num) 22 | return true; 23 | else if(mid*mid > num) 24 | right = (int)mid - 1; 25 | else left = (int)mid + 1; 26 | } 27 | return false; 28 | } 29 | } -------------------------------------------------------------------------------- /Bit-Manipulation/CalculateSquareWithoutUsingOperators.cpp: -------------------------------------------------------------------------------- 1 | // Simple solution to calculate square without 2 | // using * and pow() 3 | 4 | // If n is even, it can be written as 5 | // n = 2*x 6 | // n2 = (2*x)2 = 4*x2 7 | // If n is odd, it can be written as 8 | // n = 2*x + 1 9 | // n2 = (2*x + 1)2 = 4*x2 + 4*x + 1 10 | #include 11 | using namespace std; 12 | 13 | int square(int n) 14 | { 15 | if(n == 0) 16 | return 0; 17 | if(n < 0) 18 | n = -n; 19 | int x = n >> 1; 20 | if(n & 1) 21 | return (square(x) << 2) + (square(x) << 2) + 1; 22 | else return square(x) << 2; 23 | } 24 | 25 | // Driver code 26 | int main() 27 | { 28 | for (int n = 1; n <= 5; n++) 29 | cout << "n = " << n << ", n^2 = " << square(n) 30 | << endl; 31 | return 0; 32 | } -------------------------------------------------------------------------------- /Bit-Manipulation/CalculateSquareWithoutUsingOperators.java: -------------------------------------------------------------------------------- 1 | // Simple solution to calculate square without 2 | // using * and pow() 3 | 4 | // If n is even, it can be written as 5 | // n = 2*x 6 | // n2 = (2*x)2 = 4*x2 7 | // If n is odd, it can be written as 8 | // n = 2*x + 1 9 | // n2 = (2*x + 1)2 = 4*x2 + 4*x + 1 10 | 11 | static int square(int n) 12 | { 13 | 14 | // Base case 15 | if (n == 0) 16 | return 0; 17 | 18 | // Handle negative number 19 | if (n < 0) 20 | n = -n; 21 | 22 | // Get floor(n/2) using 23 | // right shift 24 | int x = n >> 1; 25 | 26 | // If n is odd 27 | ; 28 | if (n % 2 != 0) 29 | return ((square(x) << 2) + (x << 2) + 1); 30 | else // If n is even 31 | return (square(x) << 2); 32 | } 33 | 34 | // Driver code 35 | public static void main(String args[]) 36 | { 37 | // Function calls 38 | for (int n = 1; n <= 5; n++) 39 | System.out.println("n = " + n 40 | + " n^2 = " + square(n)); 41 | } -------------------------------------------------------------------------------- /Bit-Manipulation/ConvertANumberToHexadecimal405.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer num, return a string representing its hexadecimal representation. 2 | // For negative integers, two’s complement method is used. 3 | // All the letters in the answer string should be lowercase characters, and there should 4 | // not be any leading zeros in the answer except for the zero itself. 5 | // Note: You are not allowed to use any built-in library method to directly solve this problem. 6 | 7 | // Example 1: 8 | // Input: num = 26 9 | // Output: "1a" 10 | // Example 2: 11 | // Input: num = -1 12 | // Output: "ffffffff" 13 | 14 | // Constraints: 15 | // -231 <= num <= 231 - 1 16 | 17 | class Solution { 18 | public: 19 | string toHex(int num) { 20 | if(num == 0) return "0"; 21 | string res; 22 | int count = 0; 23 | while(num and count < 8){ 24 | int temp = num & 15; 25 | if(temp < 10) 26 | res.push_back('0' + temp); 27 | else res.push_back('a' + temp - 10); 28 | num = num >> 4; 29 | count++; 30 | } 31 | reverse(res.begin(), res.end()); 32 | return res; 33 | } 34 | }; -------------------------------------------------------------------------------- /Bit-Manipulation/ConvertANumberToHexadecimal405.java: -------------------------------------------------------------------------------- 1 | // Given an integer num, return a string representing its hexadecimal representation. 2 | // For negative integers, two’s complement method is used. 3 | // All the letters in the answer string should be lowercase characters, and there should 4 | // not be any leading zeros in the answer except for the zero itself. 5 | // Note: You are not allowed to use any built-in library method to directly solve this problem. 6 | 7 | // Example 1: 8 | // Input: num = 26 9 | // Output: "1a" 10 | // Example 2: 11 | // Input: num = -1 12 | // Output: "ffffffff" 13 | 14 | // Constraints: 15 | // -231 <= num <= 231 - 1 16 | 17 | class Solution { 18 | public String toHex(int num) { 19 | char[] map = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; 20 | if(num == 0) return "0"; 21 | String res = ""; 22 | int count = 0; 23 | while(num != 0 && count < 8){ 24 | res = map[(num & 15)] + res; 25 | num = num >> 4; 26 | count++; 27 | } 28 | return res; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Bit-Manipulation/Counting-Bits-338.java: -------------------------------------------------------------------------------- 1 | // Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i. 2 | // Example 1: 3 | // Input: n = 2 4 | // Output: [0,1,1] 5 | // Explanation: 6 | // 0 --> 0 7 | // 1 --> 1 8 | // 2 --> 10 9 | // Example 2: 10 | 11 | // Input: n = 5 12 | // Output: [0,1,1,2,1,2] 13 | // Explanation: 14 | // 0 --> 0 15 | // 1 --> 1 16 | // 2 --> 10 17 | // 3 --> 11 18 | // 4 --> 100 19 | // 5 --> 101 20 | 21 | // Constraints: 22 | 23 | // 0 <= n <= 105 24 | 25 | // Follow up: 26 | 27 | // It is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass? 28 | // Can you do it without using any built-in function (i.e., like __builtin_popcount in C++)? 29 | 30 | class Solution { 31 | public int[] countBits(int n) { 32 | int[] bits = new int[n+1]; 33 | bits[0] = 0; 34 | for(int i = 1; i <= n; i++) 35 | bits[i] = bits[i/2] + (i % 2); 36 | return bits; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Bit-Manipulation/FIndMSB.java: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Link: https://www.codingninjas.com/codestudio/problems/find-msb-in-o-1_1112570?leftPanelTab=2 3 | */ 4 | 5 | /* 6 | Time Complexity: O(1) solution to find the nearest power of 2 <= n 7 | Space complexity: O(1) 8 | */ 9 | 10 | 11 | int findMSB(int n) { 12 | 13 | n = n | n >> 1; 14 | n = n | n >> 2; 15 | n = n | n >> 4; 16 | n = n | n >> 8; 17 | n = n | n >> 16; 18 | 19 | n = n + 1; 20 | 21 | return (n >> 1); 22 | } 23 | -------------------------------------------------------------------------------- /Bit-Manipulation/FindMSB.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Link: https://www.codingninjas.com/codestudio/problems/find-msb-in-o-1_1112570?leftPanelTab=2 3 | */ 4 | 5 | /* 6 | Time Complexity: O(1) solution to find the nearest power of 2 <= n 7 | Space complexity: O(1) 8 | */ 9 | 10 | #include 11 | using namespace std; 12 | 13 | int findMSB(int n) { 14 | 15 | n = n | n >> 1; 16 | n = n | n >> 2; 17 | n = n | n >> 4; 18 | n = n | n >> 8; 19 | n = n | n >> 16; 20 | 21 | n = n + 1; 22 | 23 | return (n >> 1); 24 | } 25 | 26 | int main() { 27 | 28 | int n; 29 | cin >> n; 30 | 31 | cout << findMSB(n) << endl; 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Bit-Manipulation/HammingDistance461.cpp: -------------------------------------------------------------------------------- 1 | // The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 2 | // Given two integers x and y, return the Hamming distance between them. 3 | 4 | // Example 1: 5 | 6 | // Input: x = 1, y = 4 7 | // Output: 2 8 | // Explanation: 9 | // 1 (0 0 0 1) 10 | // 4 (0 1 0 0) 11 | // ↑ ↑ 12 | // The above arrows point to positions where the corresponding bits are different. 13 | // Example 2: 14 | 15 | // Input: x = 3, y = 1 16 | // Output: 1 17 | 18 | // Constraints: 19 | // 0 <= x, y <= 231 - 1 20 | 21 | class Solution { 22 | public: 23 | int hammingDistance(int x, int y) { 24 | int c = 0; 25 | while(x || y){ 26 | int a = x & 1, b = y & 1; 27 | c += (a == b) ? 0: 1; 28 | x = x > 0 ? x >>= 1 : 0; 29 | y = y > 0 ? y >>= 1 : 0; 30 | } 31 | return c; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Bit-Manipulation/HammingDistance461.java: -------------------------------------------------------------------------------- 1 | // The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 2 | 3 | // Given two integers x and y, return the Hamming distance between them. 4 | 5 | 6 | 7 | // Example 1: 8 | 9 | // Input: x = 1, y = 4 10 | // Output: 2 11 | // Explanation: 12 | // 1 (0 0 0 1) 13 | // 4 (0 1 0 0) 14 | // ↑ ↑ 15 | // The above arrows point to positions where the corresponding bits are different. 16 | // Example 2: 17 | 18 | // Input: x = 3, y = 1 19 | // Output: 1 20 | 21 | 22 | // Constraints: 23 | 24 | // 0 <= x, y <= 231 - 1 25 | 26 | class Solution { 27 | public int hammingDistance(int x, int y) { 28 | int c = 0; 29 | while(x > 0 || y > 0){ 30 | int a = x & 1, b = y & 1; 31 | c += (a == b) ? 0: 1; 32 | x = x > 0 ? x >>= 1 : 0; 33 | y = y > 0 ? y >>= 1 : 0; 34 | } 35 | return c; 36 | } 37 | } -------------------------------------------------------------------------------- /Bit-Manipulation/NumberComplement476.cpp: -------------------------------------------------------------------------------- 1 | // The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. 2 | 3 | // For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2. 4 | // Given an integer num, return its complement. 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 | // Example 2: 14 | 15 | // Input: num = 1 16 | // Output: 0 17 | // Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. 18 | 19 | 20 | // Constraints: 21 | // 1 <= num < 231 22 | 23 | 24 | // Note: This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/ 25 | 26 | class Solution { 27 | public: 28 | int findComplement(int num) { 29 | if(num == 0) return 1; 30 | int temp = num, bits = 1; 31 | while(temp){ 32 | num = num ^ bits; 33 | temp >>= 1; 34 | bits <<= 1; 35 | } 36 | return num; 37 | } 38 | }; 39 | 40 | -------------------------------------------------------------------------------- /Bit-Manipulation/NumberComplement476.java: -------------------------------------------------------------------------------- 1 | // The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. 2 | 3 | // For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2. 4 | // Given an integer num, return its complement. 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 | // Example 2: 14 | 15 | // Input: num = 1 16 | // Output: 0 17 | // Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. 18 | 19 | 20 | // Constraints: 21 | 22 | // 1 <= num < 231 23 | 24 | 25 | // Note: This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/ 26 | 27 | class Solution { 28 | public int findComplement(int num) { 29 | if(num == 0) return 1; 30 | int temp = num, bits = 1; 31 | while(temp > 0){ 32 | num = num ^ bits; 33 | temp >>= 1; 34 | bits <<= 1; 35 | } 36 | return num; 37 | } 38 | } -------------------------------------------------------------------------------- /Bit-Manipulation/Power-of-Two-231.java: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/power-of-2-1587115620/1# 2 | // Given a non-negative integer N. The task is to check if N is a power of 2. More formally, check if N can be expressed as 2x for some x. 3 | // Example 1: 4 | 5 | // Input: N = 1 6 | // Output: true 7 | // Explanation: 8 | // 1 is equal to 2 raised to 0 (20 = 1). 9 | // Example 2: 10 | 11 | // Input: N = 98 12 | // Output: false 13 | // Explanation: 14 | // 98 cannot be obtained by any power of 2. 15 | 16 | // Expected Time Complexity: O(log N). 17 | // Expected Auxiliary Space: O(1). 18 | 19 | // Constraints: 20 | // 0 ≤ N ≤ 1018 21 | 22 | 23 | // Method 1 24 | 25 | class Solution { 26 | public boolean isPowerOfTwo(int n) { 27 | if(n <= 0) return false; 28 | while(n%2 == 0) 29 | n /= 2; 30 | return n == 1; 31 | } 32 | } 33 | 34 | // Method 2 35 | 36 | class Solution { 37 | public boolean isPowerOfTwo(int n) { 38 | if(n <= 0) return false; 39 | int temp = n & (n-1); 40 | return temp == 0; 41 | } 42 | } -------------------------------------------------------------------------------- /Bit-Manipulation/SingleNumber136.java: -------------------------------------------------------------------------------- 1 | // Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. 2 | // You must implement a solution with a linear runtime complexity and use only constant extra space. 3 | 4 | // Example 1: 5 | 6 | // Input: nums = [2,2,1] 7 | // Output: 1 8 | // Example 2: 9 | 10 | // Input: nums = [4,1,2,1,2] 11 | // Output: 4 12 | // Example 3: 13 | 14 | // Input: nums = [1] 15 | // Output: 1 16 | 17 | // Constraints: 18 | // 1 <= nums.length <= 3 * 104 19 | // -3 * 104 <= nums[i] <= 3 * 104 20 | // Each element in the array appears twice except for one element which appears only once. 21 | 22 | // METHOD 1 23 | class Solution { 24 | public int singleNumber(int[] nums) { 25 | int ans = 0; 26 | for(int num : nums) 27 | ans ^= num; 28 | return ans; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Bit-Manipulation/SingleNumber2-137.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer array nums where every element appears three times except for one, 2 | // which appears exactly once. Find the single element and return it. 3 | // You must implement a solution with a linear runtime complexity and use only constant extra space. 4 | // Example 1: 5 | 6 | // Input: nums = [2,2,3,2] 7 | // Output: 3 8 | // Example 2: 9 | 10 | // Input: nums = [0,1,0,1,0,1,99] 11 | // Output: 99 12 | 13 | // Constraints: 14 | 15 | // 1 <= nums.length <= 3 * 104 16 | // -231 <= nums[i] <= 231 - 1 17 | // Each element in nums appears exactly three times except for one element which appears once. 18 | 19 | 20 | // METHOD 1 21 | class Solution { 22 | public: 23 | int singleNumber(vector& nums) { 24 | unordered_map m; 25 | for(auto num : nums) 26 | m[num]++; 27 | for(auto num: nums) 28 | if(m[num] == 1) 29 | return num; 30 | return -1; 31 | } 32 | }; 33 | 34 | // METHOD 2 35 | 36 | -------------------------------------------------------------------------------- /Bit-Manipulation/SingleNumber2-137.java: -------------------------------------------------------------------------------- 1 | // Given an integer array nums where every element appears three times except for one, 2 | // which appears exactly once. Find the single element and return it. 3 | // You must implement a solution with a linear runtime complexity and use only constant extra space. 4 | // Example 1: 5 | 6 | // Input: nums = [2,2,3,2] 7 | // Output: 3 8 | // Example 2: 9 | 10 | // Input: nums = [0,1,0,1,0,1,99] 11 | // Output: 99 12 | 13 | // Constraints: 14 | 15 | // 1 <= nums.length <= 3 * 104 16 | // -231 <= nums[i] <= 231 - 1 17 | // Each element in nums appears exactly three times except for one element which appears once. 18 | 19 | -------------------------------------------------------------------------------- /Design/IteratorForCombination1286.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devangi2000/Data-Structures-Algorithms-Handbook/127615e814dc3a53e25e01be86fadab458050ec0/Design/IteratorForCombination1286.cpp -------------------------------------------------------------------------------- /Design/IteratorForCombination1286.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devangi2000/Data-Structures-Algorithms-Handbook/127615e814dc3a53e25e01be86fadab458050ec0/Design/IteratorForCombination1286.java -------------------------------------------------------------------------------- /Dynamic Programming/BestTimeToBuyAndSellStockWithTransactionFee714.java: -------------------------------------------------------------------------------- 1 | // You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee. 2 | 3 | // Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. 4 | 5 | // Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). 6 | 7 | 8 | 9 | // Example 1: 10 | 11 | // Input: prices = [1,3,2,8,4,9], fee = 2 12 | // Output: 8 13 | // Explanation: The maximum profit can be achieved by: 14 | // - Buying at prices[0] = 1 15 | // - Selling at prices[3] = 8 16 | // - Buying at prices[4] = 4 17 | // - Selling at prices[5] = 9 18 | // The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8. 19 | 20 | 21 | class Solution { 22 | public int maxProfit(int[] prices, int fee) { 23 | int hold = -prices[0], cash = 0; 24 | for(int i = 1; i < prices.length; i++){ 25 | cash = Math.max(cash, hold + prices[i] - fee); 26 | hold = Math.max(hold, cash - prices[i]); 27 | } 28 | return cash; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Dynamic Programming/ClimbingStairs70.cpp: -------------------------------------------------------------------------------- 1 | // You are climbing a staircase. It takes n steps to reach the top. 2 | 3 | // Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 4 | 5 | // Example 1: 6 | 7 | // Input: n = 2 8 | // Output: 2 9 | // Explanation: There are two ways to climb to the top. 10 | // 1. 1 step + 1 step 11 | // 2. 2 steps 12 | // Example 2: 13 | 14 | // Input: n = 3 15 | // Output: 3 16 | // Explanation: There are three ways to climb to the top. 17 | // 1. 1 step + 1 step + 1 step 18 | // 2. 1 step + 2 steps 19 | // 3. 2 steps + 1 step 20 | 21 | // Constraints: 22 | 23 | // 1 <= n <= 45 24 | 25 | class Solution { 26 | public: 27 | int climbStairs(int n) { 28 | vector dp(n+1); 29 | dp[0] = 1; 30 | dp[1] = 1; 31 | for(int i=2; i<=n; i++){ 32 | dp[i] = dp[i-1] + dp[i-2]; 33 | } 34 | return dp[n]; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Dynamic Programming/ClimbingStairs70.java: -------------------------------------------------------------------------------- 1 | // You are climbing a staircase. It takes n steps to reach the top. 2 | 3 | // Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 4 | 5 | // Example 1: 6 | 7 | // Input: n = 2 8 | // Output: 2 9 | // Explanation: There are two ways to climb to the top. 10 | // 1. 1 step + 1 step 11 | // 2. 2 steps 12 | // Example 2: 13 | 14 | // Input: n = 3 15 | // Output: 3 16 | // Explanation: There are three ways to climb to the top. 17 | // 1. 1 step + 1 step + 1 step 18 | // 2. 1 step + 2 steps 19 | // 3. 2 steps + 1 step 20 | 21 | // Constraints: 22 | 23 | // 1 <= n <= 45 24 | 25 | class Solution { 26 | public int climbStairs(int n) { 27 | int[] dp = new int[n+1]; 28 | dp[0] = dp[1] = 1; 29 | for(int i = 2; i <= n; i++){ 30 | dp[i] = dp[i-1] + dp[i-2]; 31 | } 32 | return dp[n]; 33 | } 34 | } -------------------------------------------------------------------------------- /Dynamic Programming/Delete-Operation-for-Two-Strings-583.cpp: -------------------------------------------------------------------------------- 1 | // Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same. 2 | 3 | // In one step, you can delete exactly one character in either string. 4 | // Example 1: 5 | 6 | // Input: word1 = "sea", word2 = "eat" 7 | // Output: 2 8 | // Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea". 9 | // Example 2: 10 | 11 | // Input: word1 = "leetcode", word2 = "etco" 12 | // Output: 4 13 | 14 | class Solution { 15 | public: 16 | int minDistance(string word1, string word2) { 17 | int n = word1.size(), m = word2.size(); 18 | vector> dp(n+1, vector(m+1,0)); 19 | for(int i=0; i<=n; i++){ 20 | for(int j=0; j<=m; j++){ 21 | if(i==0 || j==0) dp[i][j] = 0; 22 | else if(word1[i-1] == word2[j-1]) dp[i][j] = 1 + dp[i-1][j-1]; 23 | else dp[i][j] = max(dp[i-1][j], dp[i][j-1]); 24 | } 25 | } 26 | return m+n-(2*(dp[n][m])); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Dynamic Programming/Fibonacci/FibonacciNumber509.cpp: -------------------------------------------------------------------------------- 1 | // The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, 2 | 3 | // F(0) = 0, F(1) = 1 4 | // F(n) = F(n - 1) + F(n - 2), for n > 1. 5 | // Given n, calculate F(n). 6 | 7 | 8 | 9 | // Example 1: 10 | 11 | // Input: n = 2 12 | // Output: 1 13 | // Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. 14 | // Example 2: 15 | 16 | // Input: n = 3 17 | // Output: 2 18 | // Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. 19 | // Example 3: 20 | 21 | // Input: n = 4 22 | // Output: 3 23 | // Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. 24 | 25 | 26 | // Constraints: 27 | 28 | // 0 <= n <= 30 29 | 30 | class Solution { 31 | public: 32 | int fib(int n) { 33 | if(n <= 1) return n; 34 | return fib(n-1) + fib(n-2); 35 | } 36 | }; 37 | 38 | // OR 39 | 40 | class Solution { 41 | public: 42 | int fib(int n) { 43 | if(n <= 1) return n; 44 | int a = 0, b = 1; 45 | for(int i = 2; i <= n; i++){ 46 | int temp = a + b; 47 | a = b; 48 | b = temp; 49 | } 50 | return b; 51 | } 52 | }; -------------------------------------------------------------------------------- /Dynamic Programming/Fibonacci/FibonacciNumber509.java: -------------------------------------------------------------------------------- 1 | // The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, 2 | 3 | // F(0) = 0, F(1) = 1 4 | // F(n) = F(n - 1) + F(n - 2), for n > 1. 5 | // Given n, calculate F(n). 6 | 7 | 8 | 9 | // Example 1: 10 | 11 | // Input: n = 2 12 | // Output: 1 13 | // Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. 14 | // Example 2: 15 | 16 | // Input: n = 3 17 | // Output: 2 18 | // Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. 19 | // Example 3: 20 | 21 | // Input: n = 4 22 | // Output: 3 23 | // Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. 24 | 25 | 26 | // Constraints: 27 | 28 | // 0 <= n <= 30 29 | 30 | class Solution { 31 | public int fib(int n) { 32 | if(n <= 1) return n; 33 | return fib(n-1) + fib(n-2); 34 | } 35 | } 36 | 37 | // OR 38 | 39 | class Solution { 40 | public int fib(int n) { 41 | if(n <= 1) return n; 42 | int a = 0, b = 1; 43 | for(int i = 2; i <= n; i++){ 44 | int temp = a + b; 45 | a = b; 46 | b = temp; 47 | } 48 | return b; 49 | } 50 | } -------------------------------------------------------------------------------- /Dynamic Programming/Fibonacci/NthTribonacciNumber1137.java: -------------------------------------------------------------------------------- 1 | // The Tribonacci sequence Tn is defined as follows: 2 | 3 | // T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. 4 | 5 | // Given n, return the value of Tn. 6 | 7 | 8 | 9 | // Example 1: 10 | 11 | // Input: n = 4 12 | // Output: 4 13 | // Explanation: 14 | // T_3 = 0 + 1 + 1 = 2 15 | // T_4 = 1 + 1 + 2 = 4 16 | // Example 2: 17 | 18 | // Input: n = 25 19 | // Output: 1389537 20 | 21 | 22 | // Constraints: 23 | 24 | // 0 <= n <= 37 25 | // The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1. 26 | 27 | // Gives TLE 28 | class Solution { 29 | public int tribonacci(int n) { 30 | if(n <= 1) return n; 31 | if(n == 2) return 1; 32 | return tribonacci(n-1) + tribonacci(n-2) + tribonacci(n-3); 33 | } 34 | } 35 | 36 | // Do this instead 37 | 38 | class Solution { 39 | public int tribonacci(int n) { 40 | if(n <= 1) return n; 41 | if(n == 2) return 1; 42 | int[] dp = new int[n+1]; 43 | dp[0] = 0; 44 | dp[1] = 1; 45 | dp[2] = 1; 46 | for(int i = 3; i <= n; i++) 47 | dp[i] = dp[i-1] + dp[i-2] + dp[i-3]; 48 | return dp[n]; 49 | } 50 | } -------------------------------------------------------------------------------- /Dynamic Programming/Jump-Game-55.py: -------------------------------------------------------------------------------- 1 | # Given an array of non-negative integers nums, you are initially positioned at the first index of the array. 2 | # Each element in the array represents your maximum jump length at that position. 3 | # Determine if you are able to reach the last index. 4 | # Example 1: 5 | # Input: nums = [2,3,1,1,4] 6 | # Output: true 7 | # Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 8 | # Example 2: 9 | # Input: nums = [3,2,1,0,4] 10 | # Output: false 11 | # Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. 12 | # Constraints: 13 | # 1 <= nums.length <= 104 14 | # 0 <= nums[i] <= 105 15 | 16 | 17 | class Solution: 18 | def canJump(self, nums: List[int]) -> bool: 19 | reachable = 0 20 | for i in range(len(nums)): 21 | if i>reachable: 22 | return False 23 | reachable = max(reachable, nums[i]+i) 24 | return True 25 | -------------------------------------------------------------------------------- /Dynamic Programming/JumpGame55.cpp: -------------------------------------------------------------------------------- 1 | // You are given an integer array nums. You are initially positioned at the array's first index, 2 | // and each element in the array represents your maximum jump length at that position. 3 | // Return true if you can reach the last index, or false otherwise. 4 | // Example 1: 5 | 6 | // Input: nums = [2,3,1,1,4] 7 | // Output: true 8 | // Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 9 | // Example 2: 10 | 11 | // Input: nums = [3,2,1,0,4] 12 | // Output: false 13 | // Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, 14 | // which makes it impossible to reach the last index. 15 | 16 | // Constraints: 17 | 18 | // 1 <= nums.length <= 104 19 | // 0 <= nums[i] <= 105 20 | 21 | class Solution { 22 | public: 23 | bool canJump(vector& nums) { 24 | int n = nums.size(), farthest = 0; 25 | for(int i = 0; i < nums.size() and i <= farthest; i++){ 26 | farthest = max(farthest, i + nums[i]); 27 | } 28 | return farthest >= n-1; 29 | } 30 | }; -------------------------------------------------------------------------------- /Dynamic Programming/Kadane's Algorithm/Kadane's-Algorithm.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public static long maxSubarraySum(int[] arr, int n) { 3 | long sumtillhere = 0, maxtillhere = 0; 4 | for(int i = 0; i < n; i++){ 5 | sumtillhere = Math.max((long)sumtillhere + (long)arr[i], (long)arr[i]); 6 | maxtillhere = Math.max((long)maxtillhere, (long)sumtillhere); 7 | } 8 | return maxtillhere; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Dynamic Programming/Kadane's Algorithm/maximum-subarray.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 2 | 3 | 4 | 5 | // Example 1: 6 | 7 | // Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 8 | // Output: 6 9 | // Explanation: [4,-1,2,1] has the largest sum = 6. 10 | // Example 2: 11 | 12 | // Input: nums = [1] 13 | // Output: 1 14 | // Example 3: 15 | 16 | // Input: nums = [5,4,-1,7,8] 17 | // Output: 23 18 | 19 | 20 | // Constraints: 21 | 22 | // 1 <= nums.length <= 3 * 104 23 | // -105 <= nums[i] <= 105 24 | 25 | 26 | class Solution { 27 | public: 28 | int maxSubArray(vector& nums) { 29 | int sm = 0, ans = INT_MIN; 30 | for(int i=0; i& nums) { 4 | int n = nums.size(), ans = 0; 5 | vector dp1(n, 1); 6 | vector dp2(n, 1); 7 | for(int i = 0; i < n; i++) { 8 | for(int j = 0; j < i; j++) { 9 | if(nums[i] > nums[j] && dp1[i] < 1 + dp1[j]) 10 | dp1[i] = 1 + dp1[j]; 11 | } 12 | } 13 | 14 | for(int i = n-1; i >= 0; i--) { 15 | for(int j = n-1; j > i; j--) { 16 | if(nums[j] < nums[i] && dp2[i] < 1 + dp2[j]) 17 | dp2[i] = 1 + dp2[j]; 18 | } 19 | } 20 | 21 | for(int i = 0; i < n; i++){ 22 | if(dp1[i] == 1 || dp2[i] == 1) continue; 23 | ans = max(ans, dp1[i] + dp2[i] - 1); 24 | } 25 | 26 | return ans; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Dynamic Programming/Longest Increasing Subsequence/LongestStringChain.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int util(string &word1, string &word2) { 4 | int len1 = word1.size(), len2 = word2.size(), first = 0, second = 0; 5 | if (len1 + 1 != len2 ) return false; 6 | 7 | while(second < len2) { 8 | if(first < len1 && word1[first] == word2[second]){ 9 | first++; 10 | second++; 11 | } else second++; 12 | } 13 | if(first == len1 && second == len2) return true; 14 | return false; 15 | } 16 | 17 | static bool cmp(string &s1, string &s2){ 18 | return s1.size() < s2.size(); 19 | } 20 | 21 | int longestStrChain(vector& words) { 22 | int n = words.size(); 23 | int ans = 1; 24 | vector dp(n, 1); 25 | sort(words.begin(), words.end(), cmp); 26 | for(int i = 0; i < n; i++){ 27 | for(int j = 0; j < i; j++){ 28 | if(util(words[j], words[i]) && dp[i] < dp[j] + 1) { 29 | dp[i] = dp[j] + 1; 30 | } 31 | } 32 | ans = max(ans, dp[i]); 33 | } 34 | return ans; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Dynamic Programming/Longest Increasing Subsequence/MinimumNumberOfRemovalsToMakeMountainArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumMountainRemovals(vector& nums) { 4 | int n = nums.size(), ans = 0; 5 | vector dp1(n, 1); 6 | vector dp2(n, 1); 7 | for(int i = 0; i < n; i++) { 8 | for(int j = 0; j < i; j++) { 9 | if(nums[i] > nums[j] && dp1[i] < 1 + dp1[j]) 10 | dp1[i] = 1 + dp1[j]; 11 | } 12 | } 13 | 14 | for(int i = n-1; i >= 0; i--) { 15 | for(int j = n-1; j > i; j--) { 16 | if(nums[j] < nums[i] && dp2[i] < 1 + dp2[j]) 17 | dp2[i] = 1 + dp2[j]; 18 | } 19 | } 20 | 21 | for(int i = 0; i < n; i++){ 22 | if(dp1[i] == 1 || dp2[i] == 1) continue; 23 | ans = max(ans, dp1[i] + dp2[i] - 1); 24 | } 25 | 26 | return n - ans; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Dynamic Programming/Longest Increasing Subsequence/NumberOfLIS.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findNumberOfLIS(vector& nums) { 4 | int n = nums.size(), ans = 0, c = 0; 5 | vector dp(n, 1); 6 | vector count(n, 1); 7 | for(int i = 0; i < n; i++) { 8 | for(int j = 0; j < i; j++) { 9 | if(nums[i] > nums[j] && dp[i] < 1 + dp[j]){ 10 | dp[i] = 1 + dp[j]; 11 | count[i] = count[j]; 12 | } else if(nums[i] > nums[j] && dp[i] == 1 + dp[j]) 13 | count[i] += count[j]; 14 | } 15 | ans = max(ans, dp[i]); 16 | } 17 | 18 | for(int i = 0; i < n; i++){ 19 | if(dp[i] == ans) 20 | c += count[i]; 21 | } 22 | 23 | return c; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Dynamic Programming/Longest Increasing Subsequence/NumberOfLongestIncreasingSubsequence673.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devangi2000/Data-Structures-Algorithms-Handbook/127615e814dc3a53e25e01be86fadab458050ec0/Dynamic Programming/Longest Increasing Subsequence/NumberOfLongestIncreasingSubsequence673.cpp -------------------------------------------------------------------------------- /Dynamic Programming/Longest Increasing Subsequence/NumberOfLongestIncreasingSubsequence673.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devangi2000/Data-Structures-Algorithms-Handbook/127615e814dc3a53e25e01be86fadab458050ec0/Dynamic Programming/Longest Increasing Subsequence/NumberOfLongestIncreasingSubsequence673.java -------------------------------------------------------------------------------- /Dynamic Programming/Longest Increasing Subsequence/PrintLIS.cpp: -------------------------------------------------------------------------------- 1 | public: 2 | vector longestIncreasingSubsequence(int n, vector& arr) { 3 | vector dp(n, 1); 4 | vector hash(n, 1); 5 | int lastIndex = 0, ans = 1; 6 | for(int ind = 0; ind <= n-1 ; ind++){ 7 | hash[ind] = ind; 8 | for(int prev = 0; prev <= ind-1 ; prev++){ 9 | if(arr[ind] > arr[prev] && dp[ind] < 1 + dp[prev]){ 10 | dp[ind] = 1 + dp[prev]; 11 | hash[ind] = prev; 12 | } 13 | } 14 | if(dp[ind] > ans) { 15 | ans = dp[ind]; 16 | lastIndex = ind; 17 | } 18 | } 19 | vector res; 20 | res.push_back(arr[lastIndex]); 21 | 22 | while(hash[lastIndex] != lastIndex){ 23 | lastIndex = hash[lastIndex]; 24 | res.push_back(arr[lastIndex]); 25 | } 26 | reverse(res.begin(), res.end()); 27 | return res; 28 | } 29 | -------------------------------------------------------------------------------- /Dynamic Programming/Longest Increasing Subsequence/TheNumberOfWeakCharactersInTheGame1996.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devangi2000/Data-Structures-Algorithms-Handbook/127615e814dc3a53e25e01be86fadab458050ec0/Dynamic Programming/Longest Increasing Subsequence/TheNumberOfWeakCharactersInTheGame1996.cpp -------------------------------------------------------------------------------- /Dynamic Programming/Longest-Increasing-Subsequence-300.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer array nums, return the length of the longest strictly increasing subsequence. 2 | 3 | // A subsequence is a sequence that can be derived from an array by deleting some or no elements without 4 | // changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. 5 | 6 | // Example 1: 7 | 8 | // Input: nums = [10,9,2,5,3,7,101,18] 9 | // Output: 4 10 | // Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 11 | // Example 2: 12 | 13 | // Input: nums = [0,1,0,3,2,3] 14 | // Output: 4 15 | // Example 3: 16 | 17 | // Input: nums = [7,7,7,7,7,7,7] 18 | // Output: 1 19 | 20 | class Solution { 21 | public: 22 | int lengthOfLIS(vector& nums) { 23 | int n = nums.size(), ans = 1; 24 | vector dp(n+1, 1); 25 | for(int i=0; i nums[j]){ 28 | dp[i] = max(dp[i], 1+dp[j]); 29 | ans = max(ans, dp[i]); 30 | } 31 | } 32 | } 33 | return ans; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Dynamic Programming/Longest-Palindrome-409.cpp: -------------------------------------------------------------------------------- 1 | // Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. 2 | 3 | // Letters are case sensitive, for example, "Aa" is not considered a palindrome here. 4 | 5 | // Example 1: 6 | 7 | // Input: s = "abccccdd" 8 | // Output: 7 9 | // Explanation: 10 | // One longest palindrome that can be built is "dccaccd", whose length is 7. 11 | // Example 2: 12 | 13 | // Input: s = "a" 14 | // Output: 1 15 | // Example 3: 16 | 17 | // Input: s = "bb" 18 | // Output: 2 19 | 20 | class Solution { 21 | public: 22 | int longestPalindrome(string s) { 23 | map m; 24 | int count = 0; 25 | int n = s.size(); 26 | bool odd = false; 27 | for(int i=0; i>& matrix) { 19 | int rows = matrix.size(); 20 | if(rows == 0) return 0; 21 | int cols = matrix[0].size(), largest = 0; 22 | vector> dp(rows+1, vector(cols+1, 0)); 23 | for(int i = 1; i<= rows; ++i){ 24 | for(int j = 1; j<= cols; ++j){ 25 | if(matrix[i-1][j-1]-'0'==1){ 26 | dp[i][j] = 1 + min(dp[i-1][j], min(dp[i][j-1], dp[i-1][j-1])); 27 | largest = max(largest, dp[i][j]); 28 | } 29 | } 30 | } 31 | return largest*largest; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Dynamic Programming/MaximalSquare221.java: -------------------------------------------------------------------------------- 1 | // Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. 2 | 3 | // Example 1: 4 | // Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] 5 | // Output: 4 6 | // Example 2: 7 | 8 | // Input: matrix = [["0","1"],["1","0"]] 9 | // Output: 1 10 | // Example 3: 11 | 12 | // Input: matrix = [["0"]] 13 | // Output: 0 14 | 15 | 16 | class Solution { 17 | public int maximalSquare(char[][] matrix) { 18 | int rows = matrix.length, cols = matrix[0].length, largest = 0; 19 | if(rows == 0) return 0; 20 | int[][] dp = new int[rows+1][cols+1]; 21 | for(int i = 1; i <= rows; ++i){ 22 | for(int j = 1; j <= cols; ++j){ 23 | if(matrix[i-1][j-1] - '0' == 1){ 24 | dp[i][j] = 1 + Math.min(dp[i-1][j-1], (Math.min(dp[i-1][j], dp[i][j-1]))); 25 | largest = Math.max(largest, dp[i][j]); 26 | } 27 | } 28 | } 29 | return largest*largest; 30 | } 31 | } -------------------------------------------------------------------------------- /Dynamic Programming/MaximumLengthOfRepeatedSubarray718.cpp: -------------------------------------------------------------------------------- 1 | // Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays. 2 | // Example 1: 3 | 4 | // Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7] 5 | // Output: 3 6 | // Explanation: The repeated subarray with maximum length is [3,2,1]. 7 | // Example 2: 8 | 9 | // Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0] 10 | // Output: 5 11 | 12 | // Constraints: 13 | // 1 <= nums1.length, nums2.length <= 1000 14 | // 0 <= nums1[i], nums2[i] <= 100 15 | 16 | class Solution { 17 | public: 18 | int findLength(vector& nums1, vector& nums2) { 19 | int n = nums1.size(), m = nums2.size(), maxi = INT_MIN; 20 | vector> dp(n+1, vector(m+1, 0)); 21 | for(int i = 1; i <= n; i++){ 22 | for(int j = 1; j <= m; j++){ 23 | if(nums1[i-1] == nums2[j-1]) 24 | dp[i][j] = 1 + dp[i-1][j-1]; 25 | else 26 | dp[i][j] = 0; 27 | maxi = max(maxi, dp[i][j]); 28 | } 29 | } 30 | return maxi; 31 | } 32 | }; -------------------------------------------------------------------------------- /Dynamic Programming/MaximumLengthOfRepeatedSubarray718.java: -------------------------------------------------------------------------------- 1 | // Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays. 2 | // Example 1: 3 | 4 | // Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7] 5 | // Output: 3 6 | // Explanation: The repeated subarray with maximum length is [3,2,1]. 7 | // Example 2: 8 | 9 | // Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0] 10 | // Output: 5 11 | 12 | // Constraints: 13 | // 1 <= nums1.length, nums2.length <= 1000 14 | // 0 <= nums1[i], nums2[i] <= 100 15 | 16 | class Solution { 17 | public int findLength(int[] nums1, int[] nums2) { 18 | int maxi = Integer.MIN_VALUE, n1 = nums1.length, n2 = nums2.length; 19 | int[][] dp = new int[n1+1][n2+1]; 20 | for(int i = 0; i <= n1; i++){ 21 | for(int j = 0; j <= n2; j++){ 22 | if(i == 0 || j == 0) 23 | dp[i][j] = 0; 24 | else if(nums1[i-1] == nums2[j-1]) 25 | dp[i][j] = 1 + dp[i-1][j-1]; 26 | else 27 | dp[i][j] = 0; 28 | maxi = Math.max(maxi, dp[i][j]); 29 | } 30 | } 31 | return maxi; 32 | } 33 | } -------------------------------------------------------------------------------- /Dynamic Programming/MinCostClimbingStairs746.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devangi2000/Data-Structures-Algorithms-Handbook/127615e814dc3a53e25e01be86fadab458050ec0/Dynamic Programming/MinCostClimbingStairs746.cpp -------------------------------------------------------------------------------- /Dynamic Programming/MinCostClimbingStairs746.java: -------------------------------------------------------------------------------- 1 | // You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. 2 | 3 | // You can either start from the step with index 0, or the step with index 1. 4 | 5 | // Return the minimum cost to reach the top of the floor. 6 | 7 | 8 | 9 | // Example 1: 10 | 11 | // Input: cost = [10,15,20] 12 | // Output: 15 13 | // Explanation: Cheapest is: start on cost[1], pay that cost, and go to the top. 14 | // Example 2: 15 | 16 | // Input: cost = [1,100,1,1,1,100,1,1,100,1] 17 | // Output: 6 18 | // Explanation: Cheapest is: start on cost[0], and only step on 1s, skipping cost[3]. 19 | 20 | 21 | // Constraints: 22 | 23 | // 2 <= cost.length <= 1000 24 | // 0 <= cost[i] <= 999 25 | 26 | class Solution { 27 | public int minCostClimbingStairs(int[] cost) { 28 | int n = cost.length; 29 | for(int i = 2; i < n; i++) 30 | cost[i] += Math.min(cost[i-1], cost[i-2]); 31 | return Math.min(cost[n-1], cost[n-2]); 32 | } 33 | } -------------------------------------------------------------------------------- /Dynamic Programming/Minimum-Path-Sum-64.java: -------------------------------------------------------------------------------- 1 | // Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. 2 | 3 | // Note: You can only move either down or right at any point in time. 4 | 5 | // Example 1: 6 | 7 | 8 | // Input: grid = [[1,3,1],[1,5,1],[4,2,1]] 9 | // Output: 7 10 | // Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum. 11 | // Example 2: 12 | 13 | // Input: grid = [[1,2,3],[4,5,6]] 14 | // Output: 12 15 | 16 | class Solution { 17 | public int minPathSum(int[][] grid) { 18 | int n = grid.length, m = grid[0].length; 19 | int[][] dp = new int[n][m]; 20 | dp[0][0] = grid[0][0]; 21 | for(int i = 0; i < n; i++){ 22 | for(int j = 0; j < m; j++){ 23 | if(i == 0 && j == 0) continue; 24 | else if(i == 0) dp[i][j] = grid[i][j] + dp[i][j-1]; 25 | else if(j == 0) dp[i][j] = grid[i][j] + dp[i-1][j]; 26 | else dp[i][j] = grid[i][j] + Math.min(dp[i][j-1], dp[i-1][j]); 27 | } 28 | } 29 | return dp[n-1][m-1]; 30 | } 31 | } -------------------------------------------------------------------------------- /Dynamic Programming/Pascals-Triangle-118.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer numRows, return the first numRows of Pascal's triangle. 2 | 3 | // In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 4 | 5 | // Example 1: 6 | 7 | // Input: numRows = 5 8 | // Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] 9 | // Example 2: 10 | 11 | // Input: numRows = 1 12 | // Output: [[1]] 13 | 14 | 15 | // Constraints: 16 | 17 | // 1 <= numRows <= 30 18 | 19 | class Solution { 20 | public: 21 | vector> generate(int numRows) { 22 | vector> ans; 23 | for(int i = 0; i < numRows; i++){ 24 | vector row; 25 | for(int j = 0; j <= i; j++){ 26 | if(j == 0 or j == i) 27 | row.push_back(1); 28 | else if(i > 0 and j > 0) 29 | row.push_back(ans[i-1][j-1] + ans[i-1][j]); 30 | } 31 | ans.push_back(row); 32 | } 33 | return ans; 34 | } 35 | }; -------------------------------------------------------------------------------- /Dynamic Programming/Pascals-Triangle-118.java: -------------------------------------------------------------------------------- 1 | // Given an integer numRows, return the first numRows of Pascal's triangle. 2 | 3 | // In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 4 | 5 | // Example 1: 6 | 7 | // Input: numRows = 5 8 | // Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] 9 | // Example 2: 10 | 11 | // Input: numRows = 1 12 | // Output: [[1]] 13 | 14 | 15 | // Constraints: 16 | 17 | // 1 <= numRows <= 30 18 | 19 | class Solution { 20 | public List> generate(int numRows) { 21 | List> ans = new ArrayList<>(); 22 | for(int i = 0; i < numRows; i++){ 23 | List row = new ArrayList<>(); 24 | for(int j = 0; j <= i; j++){ 25 | if(j == 0 || j == i) 26 | row.add(1); 27 | else 28 | row.add(ans.get(i-1).get(j-1) + ans.get(i-1).get(j)); 29 | } 30 | ans.add(row); 31 | } 32 | return ans; 33 | } 34 | } -------------------------------------------------------------------------------- /Dynamic Programming/Pascals-Triangle-2-119.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. 2 | // In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 3 | 4 | // Example 1: 5 | // Input: rowIndex = 3 6 | // Output: [1,3,3,1] 7 | // Example 2: 8 | // Input: rowIndex = 0 9 | // Output: [1] 10 | // Example 3: 11 | // Input: rowIndex = 1 12 | // Output: [1,1] 13 | 14 | // Constraints: 15 | // 0 <= rowIndex <= 33 16 | 17 | // Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space? 18 | 19 | class Solution { 20 | public: 21 | vector getRow(int rowIndex) { 22 | vector ans(rowIndex + 1, 0); 23 | ans[0] = 1; 24 | for(int i = 1; i <= rowIndex; i++){ 25 | for(int j = i; j >= 1; j--) 26 | ans[j] += ans[j-1]; 27 | } 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /Dynamic Programming/Pascals-Triangle-2-119.java: -------------------------------------------------------------------------------- 1 | // Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. 2 | // In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 3 | 4 | // Example 1: 5 | // Input: rowIndex = 3 6 | // Output: [1,3,3,1] 7 | // Example 2: 8 | // Input: rowIndex = 0 9 | // Output: [1] 10 | // Example 3: 11 | // Input: rowIndex = 1 12 | // Output: [1,1] 13 | 14 | // Constraints: 15 | // 0 <= rowIndex <= 33 16 | 17 | // Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space? 18 | 19 | class Solution { 20 | public List getRow(int rowIndex) { 21 | List row = new ArrayList(); 22 | for(int i = 0; i <= rowIndex; i++){ 23 | row.add(1); 24 | for(int j = i-1; j > 0; j--) 25 | row.set(j, row.get(j-1) + row.get(j)); 26 | } 27 | return row; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Dynamic Programming/Perfect-Squares-279.java: -------------------------------------------------------------------------------- 1 | // Given an integer n, return the least number of perfect square numbers that sum to n. 2 | 3 | // A perfect square is an integer that is the square of an integer; in other words, 4 | // it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not. 5 | // Example 1: 6 | 7 | // Input: n = 12 8 | // Output: 3 9 | // Explanation: 12 = 4 + 4 + 4. 10 | // Example 2: 11 | 12 | // Input: n = 13 13 | // Output: 2 14 | // Explanation: 13 = 4 + 9. 15 | 16 | class Solution { 17 | public int numSquares(int n) { 18 | int[] dp = new int[n+1]; 19 | Arrays.fill(dp, Integer.MAX_VALUE); 20 | dp[0] = 0; 21 | for(int i = 1; i <= n; i++){ 22 | for(int j = 1; j*j <= i; j++){ 23 | dp[i] = Math.min(dp[i], 1 + dp[i-(j*j)]); 24 | } 25 | } 26 | return dp[n]; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Dynamic Programming/Perfect-Squares-DP-279.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer n, return the least number of perfect square numbers that sum to n. 2 | 3 | // A perfect square is an integer that is the square of an integer; in other words, 4 | // it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not. 5 | // Example 1: 6 | 7 | // Input: n = 12 8 | // Output: 3 9 | // Explanation: 12 = 4 + 4 + 4. 10 | // Example 2: 11 | 12 | // Input: n = 13 13 | // Output: 2 14 | // Explanation: 13 = 4 + 9. 15 | 16 | class Solution { 17 | public: 18 | int numSquares(int n) { 19 | int vals = sqrt(n); 20 | vector> dp((vals+1), vector (n+1, 0)); 21 | dp[0][0] = 1; 22 | for(int i=1; i<=n; i++){ 23 | dp[0][i] = INT_MAX-1; 24 | } 25 | for(int i=1; i<=vals; i++){ 26 | for(int j=1; j<=n; j++){ 27 | if((i*i)<= j) dp[i][j] = min(1 + dp[i][j-(i*i)], dp[i-1][j]); 28 | else dp[i][j] = dp[i-1][j]; 29 | } 30 | } 31 | return dp[vals][n]; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Dynamic Programming/Reach-a-given-score.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/reach-a-given-score-1587115621/1 2 | // Consider a game where a player can score 3 or 5 or 10 points in a move. Given a total score n, find number of distinct combinations to reach the given score. 3 | 4 | // Example: 5 | // Input 6 | // 3 7 | // 8 8 | // 20 9 | // 13 10 | // Output 11 | // 1 12 | // 4 13 | // 2 14 | // Explanation 15 | // For 1st example when n = 8 16 | // { 3, 5 } and {5, 3} are the 17 | // two possible permutations but 18 | // these represent the same 19 | // cobmination. Hence output is 1. 20 | 21 | // Constraints: 22 | // 1 ≤ T ≤ 100 23 | // 1 ≤ n ≤ 1000 24 | 25 | long long int count(long long int n) 26 | { 27 | long long int arr[] = {3, 5, 10}; 28 | long long int dp[4][n+1]; 29 | memset(dp, 0, sizeof(dp)); 30 | for(int i = 0; i < 4; i++) 31 | dp[i][0] = 1; 32 | for(int i = 1; i < 4; i++){ 33 | for(int j = 1; j <= n; j++){ 34 | if(j < arr[i-1]) 35 | dp[i][j] = dp[i-1][j]; 36 | else 37 | dp[i][j] = dp[i-1][j] + dp[i][j-arr[i-1]]; 38 | } 39 | } 40 | return dp[3][n]; 41 | } 42 | -------------------------------------------------------------------------------- /Dynamic Programming/Ugly-Number-2-264.cpp: -------------------------------------------------------------------------------- 1 | // An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. 2 | 3 | // Given an integer n, return the nth ugly number. 4 | // Example 1: 5 | 6 | // Input: n = 10 7 | // Output: 12 8 | // Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers. 9 | // Example 2: 10 | 11 | // Input: n = 1 12 | // Output: 1 13 | // Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. 14 | 15 | class Solution { 16 | public: 17 | int nthUglyNumber(int n) { 18 | vector ans(n+1); 19 | ans[0] = 1; 20 | int i2 = 0, i3 = 0, i5 = 0; 21 | for(int i=1; i catalan(n+1, 0); 20 | catalan[0] = catalan[1] = 1; 21 | for(int i = 2; i <=n; i++){ 22 | catalan[i] = 0; 23 | for(int j = 0; j < i; j++) 24 | catalan[i] += catalan[j]*catalan[i-j-1]; 25 | } 26 | return catalan[n]; 27 | } 28 | }; -------------------------------------------------------------------------------- /Dynamic Programming/Unique-Binary-Search-Trees-96.java: -------------------------------------------------------------------------------- 1 | // Given an integer n, return the number of structurally unique 2 | // BST's (binary search trees) which has exactly n nodes of 3 | // unique values from 1 to n. 4 | 5 | // Example 1: 6 | // Input: n = 3 7 | // Output: 5 8 | // Example 2: 9 | // Input: n = 1 10 | // Output: 1 11 | 12 | // Constraints: 13 | // 1 <= n <= 19 14 | 15 | class Solution { 16 | public int numTrees(int n) { 17 | int[] catalan = new int[n+1]; 18 | catalan[0] = catalan[1] = 1; 19 | for(int i = 2; i <= n; i++){ 20 | for(int j = 0; j < i; j++) 21 | catalan[i] += catalan[j] * catalan[i-j-1]; 22 | } 23 | return catalan[n]; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Dynamic Programming/UniquePaths64.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devangi2000/Data-Structures-Algorithms-Handbook/127615e814dc3a53e25e01be86fadab458050ec0/Dynamic Programming/UniquePaths64.cpp -------------------------------------------------------------------------------- /Dynamic Programming/UniquePaths64.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devangi2000/Data-Structures-Algorithms-Handbook/127615e814dc3a53e25e01be86fadab458050ec0/Dynamic Programming/UniquePaths64.java -------------------------------------------------------------------------------- /Dynamic Programming/best-time-to-buy-and-sell-stock-121.java: -------------------------------------------------------------------------------- 1 | // You are given an array prices where prices[i] is the price of a given stock on the ith day. 2 | 3 | // You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. 4 | 5 | // Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 6 | 7 | 8 | class Solution { 9 | public int maxProfit(int[] prices) { 10 | int profit = 0, mini = Integer.MAX_VALUE; 11 | for(int price : prices){ 12 | mini = Math.min(price, mini); 13 | profit = Math.max(profit, price - mini); 14 | } 15 | return profit; 16 | } 17 | } -------------------------------------------------------------------------------- /Dynamic Programming/best-time-to-buy-sell-stock-121.cpp: -------------------------------------------------------------------------------- 1 | // You are given an array prices where prices[i] is the price of a given stock on the ith day. 2 | 3 | // You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. 4 | 5 | // Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 6 | 7 | class Solution { 8 | public: 9 | int maxProfit(vector& prices) { 10 | int profit = 0, curr = INT_MAX; 11 | for(int i=0; i adj[]) { 8 | queue q; 9 | vector indegree(V, 0); 10 | for(int i = 0; i < V; i++) 11 | for(auto it : adj[i]) 12 | indegree[it]++; 13 | for(int i = 0; i < V; i++) 14 | if(indegree[i] == 0) 15 | q.push(i); 16 | int count = 0; 17 | while(!q.empty()){ 18 | int node = q.front(); q.pop(); 19 | count++; 20 | for(int it : adj[node]){ 21 | indegree[it]--; 22 | if(indegree[it] == 0) 23 | q.push(it); 24 | } 25 | } 26 | return count != V; 27 | } 28 | }; -------------------------------------------------------------------------------- /Graphs/Detect-Cycle-in-Directed-Graph-BFS.java: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/detect-cycle-in-a-directed-graph/1/?page=1&category[]=Graph&query=page1category[]Graph 2 | // Given a Directed Graph with V vertices (Numbered from 0 to V-1) and E edges, check whether it contains any cycle or not. 3 | 4 | 5 | class Solution { 6 | public boolean isCyclic(int V, ArrayList> adj) { 7 | int count = 0; 8 | int[] indegree = new int[V]; 9 | Queue q = new LinkedList<>(); 10 | for(int i = 0; i < V; i++) 11 | for(int it : adj.get(i)) 12 | indegree[it]++; 13 | for(int i = 0; i < V; i++) 14 | if(indegree[i] == 0) 15 | q.offer(i); 16 | 17 | while(!q.isEmpty()){ 18 | int curr = q.poll(); 19 | count++; 20 | for(int it : adj.get(curr)){ 21 | indegree[it]--; 22 | if(indegree[it] == 0) 23 | q.offer(it); 24 | } 25 | } 26 | return count == V ? false : true; 27 | } 28 | } -------------------------------------------------------------------------------- /Graphs/Detect-Cycle-in-Directed-Graph-DFS.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/detect-cycle-in-a-directed-graph/1/?page=1&category[]=Graph&query=page1category[]Graph 2 | // Given a Directed Graph with V vertices (Numbered from 0 to V-1) and E edges, check whether it contains any cycle or not. 3 | 4 | class Solution { 5 | public: 6 | bool checkCycle(vector adj[], int curr, vector &visited, vector &path){ 7 | visited[curr] = 1; 8 | path[curr] = 1; 9 | for(int node: adj[curr]){ 10 | if(!visited[node]){ 11 | if(checkCycle(adj, node, visited, path)) return true; 12 | } 13 | else if(path[node]) return true; 14 | } 15 | path[curr] = 0; 16 | return false; 17 | } 18 | 19 | bool isCyclic(int V, vector adj[]) { 20 | vector visited(V, 0), path(V, 0); 21 | for(int i = 0; i < V; i++){ 22 | if(!visited[i]) 23 | if(checkCycle(adj, i, visited, path)) 24 | return true; 25 | } 26 | return false; 27 | } 28 | }; -------------------------------------------------------------------------------- /Graphs/Detect-Cycle-in-Directed-Graph-DFS.java: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/detect-cycle-in-a-directed-graph/1/?page=1&category[]=Graph&query=page1category[]Graph 2 | // Given a Directed Graph with V vertices (Numbered from 0 to V-1) and E edges, check whether it contains any cycle or not. 3 | 4 | class Solution { 5 | public boolean checkCycle(ArrayList> adj, int curr, int[] visited, int[] path){ 6 | visited[curr] = 1; 7 | path[curr] = 1; 8 | for(int node : adj.get(curr)){ 9 | if(visited[node] == 0){ 10 | if(checkCycle(adj, node, visited, path) == true) return true; 11 | } 12 | else if(path[node] == 1) return true; 13 | } 14 | path[curr] = 0; 15 | return false; 16 | } 17 | 18 | public boolean isCyclic(int V, ArrayList> adj) { 19 | int[] visited = new int[V]; 20 | int[] path = new int[V]; 21 | for(int i = 0; i < V; i++){ 22 | if(visited[i] == 0) 23 | if(checkCycle(adj, i, visited, path) == true) return true; 24 | } 25 | return false; 26 | } 27 | } -------------------------------------------------------------------------------- /Graphs/NetworkDelayTime743.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devangi2000/Data-Structures-Algorithms-Handbook/127615e814dc3a53e25e01be86fadab458050ec0/Graphs/NetworkDelayTime743.cpp -------------------------------------------------------------------------------- /Graphs/NetworkDelayTime743.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devangi2000/Data-Structures-Algorithms-Handbook/127615e814dc3a53e25e01be86fadab458050ec0/Graphs/NetworkDelayTime743.java -------------------------------------------------------------------------------- /Greedy-Algo/Jump-Game-2-45.cpp: -------------------------------------------------------------------------------- 1 | // Given an array of non-negative integers nums, you are initially positioned at the first index of the array. 2 | // Each element in the array represents your maximum jump length at that position. 3 | // Your goal is to reach the last index in the minimum number of jumps. 4 | // You can assume that you can always reach the last index. 5 | 6 | // Example 1: 7 | 8 | // Input: nums = [2,3,1,1,4] 9 | // Output: 2 10 | // Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. 11 | // Example 2: 12 | 13 | // Input: nums = [2,3,0,1,4] 14 | // Output: 2 15 | 16 | // Constraints: 17 | 18 | // 1 <= nums.length <= 104 19 | // 0 <= nums[i] <= 1000 20 | 21 | class Solution { 22 | public: 23 | int jump(vector& nums) { 24 | int jumps = 0, left = 0, right = 0; 25 | while(right < nums.size()-1){ 26 | int farthest = 0; 27 | for(int i = left; i <= right; i++){ 28 | farthest = max(farthest, i + nums[i]); 29 | } 30 | left = right + 1; 31 | right = farthest; 32 | jumps++; 33 | } 34 | return jumps; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Greedy-Algo/Maximize-Toys.cpp: -------------------------------------------------------------------------------- 1 | // Given an array arr[ ] of length N consisting cost of N 2 | // toys and an integer K depicting the amount with you. Your task 3 | // is to find maximum number of toys you can buy with K amount. 4 | 5 | // Example 1: 6 | 7 | // Input: 8 | // N = 7 9 | // K = 50 10 | // arr[] = {1, 12, 5, 111, 200, 1000, 10} 11 | // Output: 4 12 | // Explaination: The costs of the toys 13 | // you can buy are 1, 12, 5 and 10. 14 | // Example 2: 15 | 16 | // Input: 17 | // N = 3 18 | // K = 100 19 | // arr[] = {20, 30, 50} 20 | // Output: 3 21 | // Explaination: You can buy all toys. 22 | 23 | // Expected Time Complexity: O(N * Log(N)) 24 | // Expected Auxiliary Space: O(1) 25 | 26 | // Constraints: 27 | // 1 ≤ N ≤ 105 28 | // 1 ≤ K, arr[i] ≤ 109 29 | 30 | class Solution{ 31 | public: 32 | int toyCount(int N, int K, vector arr) 33 | { 34 | if(N == 0 or K == 0) return 0; 35 | sort(arr.begin(), arr.end()); 36 | int count = 0, sum = 0, i=0; 37 | while(i= 0){ 38 | K -= arr[i++]; 39 | } 40 | return i; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Greedy-Algo/Merge Overlapping Questions.txt: -------------------------------------------------------------------------------- 1 | 56 Merge Intervals <- very similar😈 2 | 435 Non-overlapping Intervals <- very similar😈 3 | 252 Meeting Rooms 4 | 253 Meeting Rooms II 5 | 452. Minimum Number of Arrows to Burst Balloons -------------------------------------------------------------------------------- /Hashing/DistantBarcodes1054.cpp: -------------------------------------------------------------------------------- 1 | // In a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i]. 2 | // Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, 3 | // and it is guaranteed an answer exists. 4 | 5 | // Example 1: 6 | // Input: barcodes = [1,1,1,2,2,2] 7 | // Output: [2,1,2,1,2,1] 8 | // Example 2: 9 | // Input: barcodes = [1,1,1,1,2,2,3,3] 10 | // Output: [1,3,1,3,1,2,1,2] 11 | 12 | // Constraints: 13 | // 1 <= barcodes.length <= 10000 14 | // 1 <= barcodes[i] <= 10000 15 | 16 | class Solution { 17 | public: 18 | vector rearrangeBarcodes(vector& barcodes) { 19 | unordered_map m; 20 | for(auto code : barcodes) 21 | m[code]++; 22 | set> s; 23 | for(auto it = m.begin(); it != m.end(); ++it) 24 | s.insert({it->second, it->first}); 25 | int pos = 0; 26 | for(auto it = s.rbegin(); it != s.rend(); ++it){ 27 | for(auto count = 0; count < it->first; ++count, pos += 2){ 28 | if(pos >= barcodes.size()) pos = 1; 29 | barcodes[pos] = it->second; 30 | } 31 | } 32 | return barcodes; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Hashing/LargestSubarrayWithZeroSum.java: -------------------------------------------------------------------------------- 1 | // Given an array having both positive and negative integers. The task is to compute the length of the largest subarray with sum 0. 2 | 3 | // Example 1: 4 | 5 | // Input: 6 | // N = 8 7 | // A[] = {15,-2,2,-8,1,7,10,23} 8 | // Output: 5 9 | // Explanation: The largest subarray with 10 | // sum 0 will be -2 2 -8 1 7. 11 | // Your Task: 12 | // You just have to complete the function maxLen() which takes two arguments an array A and n, where n is the size of the array A and returns the length of the largest subarray with 0 sum. 13 | 14 | // Expected Time Complexity: O(N). 15 | // Expected Auxiliary Space: O(N). 16 | 17 | // Constraints: 18 | // 1 <= N <= 105 19 | // -1000 <= A[i] <= 1000, for each valid i 20 | 21 | class GfG 22 | { 23 | int maxLen(int arr[], int n) 24 | { 25 | int maxi = 0, sum = 0; 26 | Map mp = new HashMap<>(); 27 | for(int i = 0; i < n; i++){ 28 | sum += arr[i]; 29 | if(sum == 0) 30 | maxi = Math.max(maxi, i+1); 31 | else if(mp.containsKey(sum)) 32 | maxi = Math.max(maxi, i - mp.get(sum)); 33 | else mp.put(sum, i); 34 | } 35 | return maxi; 36 | } 37 | } -------------------------------------------------------------------------------- /Hashing/LongestConsecutiveSequence128.cpp: -------------------------------------------------------------------------------- 1 | // Given an unsorted array of integers nums, return the length of the longest consecutive elements 2 | // sequence. 3 | // You must write an algorithm that runs in O(n) time. 4 | 5 | // Example 1: 6 | 7 | // Input: nums = [100,4,200,1,3,2] 8 | // Output: 4 9 | // Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. 10 | // Example 2: 11 | 12 | // Input: nums = [0,3,7,2,5,8,4,6,0,1] 13 | // Output: 9 14 | 15 | // Constraints: 16 | // 0 <= nums.length <= 105 17 | // -109 <= nums[i] <= 109 18 | 19 | class Solution { 20 | public: 21 | int longestConsecutive(vector& nums) { 22 | int n = nums.size(), ans = 0, len = 0; 23 | set s(nums.begin(), nums.end()); 24 | for(auto x : nums){ 25 | if(s.find(x - 1) == s.end()){ 26 | int y = x + 1; 27 | while(s.find(y) != s.end()) 28 | y++; 29 | ans = max(ans, y-x); 30 | } 31 | } 32 | return ans; 33 | } 34 | }; -------------------------------------------------------------------------------- /Hashing/LongestConsecutiveSequence128.java: -------------------------------------------------------------------------------- 1 | // Given an unsorted array of integers nums, return the length of the longest consecutive elements 2 | // sequence. 3 | // You must write an algorithm that runs in O(n) time. 4 | 5 | // Example 1: 6 | 7 | // Input: nums = [100,4,200,1,3,2] 8 | // Output: 4 9 | // Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. 10 | // Example 2: 11 | 12 | // Input: nums = [0,3,7,2,5,8,4,6,0,1] 13 | // Output: 9 14 | 15 | // Constraints: 16 | // 0 <= nums.length <= 105 17 | // -109 <= nums[i] <= 109 18 | 19 | class Solution { 20 | public int longestConsecutive(int[] nums) { 21 | Set s = new HashSet<>(); 22 | for(int num : nums) 23 | s.add(num); 24 | int curr = 0, longest = 0; 25 | for(int num : nums){ 26 | if(!s.contains(num-1)){ 27 | curr = num+1; 28 | while(s.contains(curr)) 29 | ++curr; 30 | longest = Math.max(longest, curr - num); 31 | } 32 | } 33 | return longest; 34 | } 35 | } -------------------------------------------------------------------------------- /Hashing/longest-substring-without-repeating-characters.cpp: -------------------------------------------------------------------------------- 1 | // Given a string s, find the length of the longest substring without repeating characters. 2 | 3 | // Example 1: 4 | 5 | // Input: s = "abcabcbb" 6 | // Output: 3 7 | // Explanation: The answer is "abc", with the length of 3. 8 | // Example 2: 9 | 10 | // Input: s = "bbbbb" 11 | // Output: 1 12 | // Explanation: The answer is "b", with the length of 1. 13 | // Example 3: 14 | 15 | // Input: s = "pwwkew" 16 | // Output: 3 17 | // Explanation: The answer is "wke", with the length of 3. 18 | // Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. 19 | // Example 4: 20 | 21 | // Input: s = "" 22 | // Output: 0 23 | 24 | class Solution { 25 | public: 26 | int lengthOfLongestSubstring(string s) { 27 | if(s.size() <= 1) return s.size(); 28 | int left = 0, right = 0, ans = 0; 29 | unordered_map m; 30 | while(right < s.size()){ 31 | m[s[right]]++; 32 | while(m[s[right]] > 1){ 33 | m[s[left]]--; 34 | left++; 35 | } 36 | ans = max(ans, right-left+1); 37 | right++; 38 | } 39 | return ans; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Hashing/subarray-sum-divisible-by-k.cpp: -------------------------------------------------------------------------------- 1 | // Given an array nums of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by k. 2 | // Example 1: 3 | 4 | // Input: nums = [4,5,0,-2,-3,1], k = 5 5 | // Output: 7 6 | // Explanation: There are 7 subarrays with a sum divisible by k = 5: 7 | // [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3] 8 | 9 | class Solution { 10 | public: 11 | int subarraysDivByK(vector& nums, int k) { 12 | unordered_map m; 13 | m[0] = 1; 14 | 15 | int sum = 0, ans = 0; 16 | for(int i=0; i < nums.size(); ++i) { 17 | sum += nums[i]; 18 | 19 | // in cpp, mod gives negative value (unlike Python) 20 | // i.e in Python -2 % 3 = 1, in c++: -2 % 3 = -2 21 | int target = sum % k; 22 | if(target < 0) 23 | target += k; 24 | 25 | if(m.count(target) != 0) { 26 | ans += m[target]; 27 | m[target] += 1; 28 | } else 29 | m[target] = 1; 30 | } 31 | 32 | return ans; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Heap/Kth-Largest-Element-in-Array-215.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer array nums and an integer k, return the kth largest element in the array. 2 | // Note that it is the kth largest element in the sorted order, not the kth distinct element. 3 | // Example 1: 4 | 5 | // Input: nums = [3,2,1,5,6,4], k = 2 6 | // Output: 5 7 | // Example 2: 8 | 9 | // Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 10 | // Output: 4 11 | 12 | 13 | // Constraints: 14 | 15 | // 1 <= k <= nums.length <= 104 16 | // -104 <= nums[i] <= 104 17 | 18 | class Solution { 19 | public: 20 | int findKthLargest(vector& nums, int k) { 21 | priority_queue, greater> minHeap; 22 | for(auto i:nums){ 23 | minHeap.push(i); 24 | if(minHeap.size()>k) 25 | minHeap.pop(); 26 | } 27 | return minHeap.top(); 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Heap/Kth-Largest-Element-in-Array-215.java: -------------------------------------------------------------------------------- 1 | // Given an integer array nums and an integer k, return the kth largest element in the array. 2 | // Note that it is the kth largest element in the sorted order, not the kth distinct element. 3 | // Example 1: 4 | 5 | // Input: nums = [3,2,1,5,6,4], k = 2 6 | // Output: 5 7 | // Example 2: 8 | 9 | // Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 10 | // Output: 4 11 | 12 | 13 | // Constraints: 14 | 15 | // 1 <= k <= nums.length <= 104 16 | // -104 <= nums[i] <= 104 17 | class Solution { 18 | public int findKthLargest(int[] nums, int k) { 19 | Queue q = new PriorityQueue<>((a, b) -> b - a); 20 | for(int num : nums){ 21 | q.offer(num); 22 | } 23 | for(int i = 1; i < k; i++) 24 | q.poll(); 25 | return q.poll(); 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /InterviewBit/Arrays/Max-Distance.cpp: -------------------------------------------------------------------------------- 1 | // Problem Description 2 | // Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j]. 3 | 4 | // Input Format 5 | // First and only argument is an integer array A. 6 | // Output Format 7 | // Return an integer denoting the maximum value of j - i; 8 | // Example Input 9 | // Input 1: 10 | 11 | // A = [3, 5, 4, 2] 12 | // Example Output 13 | // Output 1: 14 | // 2 15 | 16 | 17 | // Example Explanation 18 | // Explanation 1: 19 | // Maximum value occurs for pair (3, 4). 20 | 21 | int Solution::maximumGap(const vector &A) { 22 | vector> v; 23 | for(int i=0; inext; 27 | while(fast->next){ 28 | slow = slow->next; 29 | fast = fast->next; 30 | } 31 | slow->next = slow->next->next; 32 | return start->next; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Linked-Lists/Rotate-List-61.cpp: -------------------------------------------------------------------------------- 1 | // Given the head of a linked list, rotate the list to the right by k places. 2 | // Example 1: 3 | 4 | // Input: head = [1,2,3,4,5], k = 2 5 | // Output: [4,5,1,2,3] 6 | // Example 2: 7 | 8 | // Input: head = [0,1,2], k = 4 9 | // Output: [2,0,1] 10 | 11 | // Constraints: 12 | 13 | // The number of nodes in the list is in the range [0, 500]. 14 | // -100 <= Node.val <= 100 15 | // 0 <= k <= 2 * 109 16 | 17 | class Solution { 18 | public: 19 | ListNode* rotateRight(ListNode* head, int k) { 20 | if(!head) return NULL; 21 | int n = 1; 22 | ListNode *curr = head, *tail = head; 23 | while(tail->next){ 24 | n++; 25 | tail = tail->next; 26 | } 27 | tail->next = head; 28 | if(k %= n) 29 | for(int i = 0; i < n-k; ++i) 30 | tail = tail->next; 31 | curr = tail->next; 32 | tail->next = NULL; 33 | return curr; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Linked-Lists/Swap-Nodes-in-Pairs-24.cpp: -------------------------------------------------------------------------------- 1 | // Given a linked list, swap every two adjacent nodes and return its head. 2 | // You must solve the problem without modifying the values in the list's 3 | // nodes (i.e., only nodes themselves may be changed.) 4 | 5 | // Example 1: 6 | // Input: head = [1,2,3,4] 7 | // Output: [2,1,4,3] 8 | // Example 2: 9 | // Input: head = [] 10 | // Output: [] 11 | // Example 3: 12 | // Input: head = [1] 13 | // Output: [1] 14 | 15 | // Constraints: 16 | 17 | // The number of nodes in the list is in the range [0, 100]. 18 | // 0 <= Node.val <= 100 19 | 20 | class Solution { 21 | public: 22 | ListNode* swapPairs(ListNode* head) { 23 | if(head == NULL or head->next == NULL) return head; 24 | ListNode* sentinel = new ListNode(0, head); 25 | ListNode* curr = sentinel; 26 | 27 | while(curr->next and curr->next->next){ 28 | ListNode *a = curr->next; 29 | ListNode *b = curr->next->next; 30 | a->next = b->next; 31 | curr->next = b; 32 | curr->next->next = a; 33 | curr = curr->next->next; 34 | } 35 | return sentinel->next; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Linked-Lists/reverse-linked-list-206.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Given the head of a singly linked list, reverse the list, and return the reversed list. 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode() : val(0), next(nullptr) {} 9 | * ListNode(int x) : val(x), next(nullptr) {} 10 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 11 | * }; 12 | */ 13 | // Iterative 14 | class Solution { 15 | public: 16 | ListNode* reverseList(ListNode* head) { 17 | if(!head) 18 | return NULL; 19 | ListNode* next, *prev = NULL, *current = head; 20 | while(current){ 21 | next = current->next; 22 | current->next = prev; 23 | prev = current; 24 | current = next; 25 | } 26 | head = prev; 27 | return head; 28 | } 29 | }; 30 | 31 | // Recursive 32 | 33 | class Solution { 34 | public: 35 | ListNode* reverseList(ListNode* head) { 36 | if(!head or !head->next) return head; 37 | ListNode *node = reverseList(head->next); 38 | head->next->next = head; 39 | head->next = NULL; 40 | return node; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Linked-Lists/reverse-linked-list-206.java: -------------------------------------------------------------------------------- 1 | 2 | // Given the head of a singly linked list, reverse the list, and return the reversed list. 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode() {} 9 | * ListNode(int val) { this.val = val; } 10 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 11 | * } 12 | */ 13 | class Solution { 14 | public ListNode reverseList(ListNode head) { 15 | if(head == null || head.next == null) return head; 16 | ListNode prev = null, curr = head, next = head.next; 17 | while(curr != null){ 18 | next = curr.next; 19 | curr.next = prev; 20 | prev = curr; 21 | curr = next; 22 | } 23 | return prev; 24 | } 25 | } 26 | 27 | 28 | // Recursive 29 | 30 | class Solution { 31 | public ListNode reverseList(ListNode head) { 32 | if(head == null || head.next == null) return head; 33 | ListNode node = reverseList(head.next); 34 | head.next.next = head; 35 | head.next = null; 36 | return node; 37 | } 38 | } -------------------------------------------------------------------------------- /Math/2KeysKeyboard650.cpp: -------------------------------------------------------------------------------- 1 | // There is only one character 'A' on the screen of a notepad. You can perform two operations on 2 | // this notepad for each step: 3 | // Copy All: You can copy all the characters present on the screen (a partial copy is not allowed). 4 | // Paste: You can paste the characters which are copied last time. 5 | // Given an integer n, return the minimum number of operations to get the character 'A' exactly n 6 | // times on the screen. 7 | // Example 1: 8 | // Input: n = 3 9 | // Output: 3 10 | // Explanation: Intitally, we have one character 'A'. 11 | // In step 1, we use Copy All operation. 12 | // In step 2, we use Paste operation to get 'AA'. 13 | // In step 3, we use Paste operation to get 'AAA'. 14 | // Example 2: 15 | // Input: n = 1 16 | // Output: 0 17 | // Constraints: 18 | // 1 <= n <= 1000 19 | 20 | class Solution { 21 | public: 22 | int minSteps(int n) { 23 | int ans = 0, i = 2; 24 | while(i <= n){ 25 | if(n % i == 0){ 26 | ans += i; 27 | n /= i; 28 | } 29 | else i++; 30 | } 31 | return ans; 32 | } 33 | }; -------------------------------------------------------------------------------- /Math/2KeysKeyboard650.java: -------------------------------------------------------------------------------- 1 | // There is only one character 'A' on the screen of a notepad. You can perform two operations on 2 | // this notepad for each step: 3 | // Copy All: You can copy all the characters present on the screen (a partial copy is not allowed). 4 | // Paste: You can paste the characters which are copied last time. 5 | // Given an integer n, return the minimum number of operations to get the character 'A' exactly n 6 | // times on the screen. 7 | // Example 1: 8 | // Input: n = 3 9 | // Output: 3 10 | // Explanation: Intitally, we have one character 'A'. 11 | // In step 1, we use Copy All operation. 12 | // In step 2, we use Paste operation to get 'AA'. 13 | // In step 3, we use Paste operation to get 'AAA'. 14 | // Example 2: 15 | // Input: n = 1 16 | // Output: 0 17 | // Constraints: 18 | // 1 <= n <= 1000 19 | 20 | class Solution { 21 | public int minSteps(int n) { 22 | int ans = 0; 23 | for(int i = 2; i <= n;){ 24 | if(n%i == 0){ 25 | ans += i; 26 | n /= i; 27 | } 28 | else i++; 29 | } 30 | return ans; 31 | } 32 | } -------------------------------------------------------------------------------- /Math/ExcelSheetColumnNumber.cpp: -------------------------------------------------------------------------------- 1 | // Given a string columnTitle that represents the column title as appear in an Excel sheet, return its corresponding column number. 2 | 3 | // For example: 4 | 5 | // A -> 1 6 | // B -> 2 7 | // C -> 3 8 | // ... 9 | // Z -> 26 10 | // AA -> 27 11 | // AB -> 28 12 | // ... 13 | 14 | 15 | // Example 1: 16 | 17 | // Input: columnTitle = "A" 18 | // Output: 1 19 | // Example 2: 20 | 21 | // Input: columnTitle = "AB" 22 | // Output: 28 23 | // Example 3: 24 | 25 | // Input: columnTitle = "ZY" 26 | // Output: 701 27 | // Example 4: 28 | 29 | // Input: columnTitle = "FXSHRXW" 30 | // Output: 2147483647 31 | 32 | 33 | // Constraints: 34 | 35 | // 1 <= columnTitle.length <= 7 36 | // columnTitle consists only of uppercase English letters. 37 | // columnTitle is in the range ["A", "FXSHRXW"]. 38 | 39 | class Solution { 40 | public: 41 | int titleToNumber(string A) { 42 | int n = A.size(), sum = 0; 43 | for(int i = 0; i < n; i++){ 44 | sum = 26*sum + (A[i]-'A'+1); 45 | } 46 | return sum; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Math/ExcelSheetColumnTitle.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. 2 | 3 | // For example: 4 | 5 | // A -> 1 6 | // B -> 2 7 | // C -> 3 8 | // ... 9 | // Z -> 26 10 | // AA -> 27 11 | // AB -> 28 12 | // ... 13 | 14 | 15 | // Example 1: 16 | 17 | // Input: columnNumber = 1 18 | // Output: "A" 19 | // Example 2: 20 | 21 | // Input: columnNumber = 28 22 | // Output: "AB" 23 | // Example 3: 24 | 25 | // Input: columnNumber = 701 26 | // Output: "ZY" 27 | // Example 4: 28 | 29 | // Input: columnNumber = 2147483647 30 | // Output: "FXSHRXW" 31 | 32 | 33 | // Constraints: 34 | 35 | // 1 <= columnNumber <= 231 - 1 36 | 37 | class Solution { 38 | public: 39 | string convertToTitle(int n) 40 | { 41 | string ans = ""; 42 | while(n > 0){ 43 | int temp = n % 26; 44 | if(temp == 0){ 45 | ans += 'Z'; 46 | n /= 26; 47 | n -= 1; 48 | } 49 | else{ 50 | ans += (temp - 1) + 'A'; 51 | n /= 26; 52 | } 53 | } 54 | reverse(ans.begin(), ans.end()); 55 | return ans; 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /Math/FactorialTrailingZeroes172.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer n, return the number of trailing zeroes in n!. 2 | // Follow up: Could you write a solution that works in logarithmic time complexity? 3 | 4 | // Example 1: 5 | // Input: n = 3 6 | // Output: 0 7 | // Explanation: 3! = 6, no trailing zero. 8 | // Example 2: 9 | // Input: n = 5 10 | // Output: 1 11 | // Explanation: 5! = 120, one trailing zero. 12 | // Example 3: 13 | // Input: n = 0 14 | // Output: 0 15 | 16 | 17 | // Constraints: 18 | // 0 <= n <= 104 19 | 20 | class Solution { 21 | public: 22 | int trailingZeroes(int n) { 23 | if(n < 5) return 0; 24 | int count = 0; 25 | for(int i = 5; n/i > 0; i*=5){ 26 | count += (n / i); 27 | } 28 | return count; 29 | } 30 | }; -------------------------------------------------------------------------------- /Math/FactorialTrailingZeroes172.java: -------------------------------------------------------------------------------- 1 | // Given an integer n, return the number of trailing zeroes in n!. 2 | // Follow up: Could you write a solution that works in logarithmic time complexity? 3 | 4 | // Example 1: 5 | // Input: n = 3 6 | // Output: 0 7 | // Explanation: 3! = 6, no trailing zero. 8 | // Example 2: 9 | // Input: n = 5 10 | // Output: 1 11 | // Explanation: 5! = 120, one trailing zero. 12 | // Example 3: 13 | // Input: n = 0 14 | // Output: 0 15 | 16 | 17 | // Constraints: 18 | // 0 <= n <= 104 19 | 20 | class Solution { 21 | public int trailingZeroes(int n) { 22 | if(n < 5) return 0; 23 | int count = 0; 24 | for(int i = 5; n/i > 0; i*=5){ 25 | count += n/i; 26 | } 27 | return count; 28 | } 29 | } -------------------------------------------------------------------------------- /Math/MonotoneIncreasingDigits738.cpp: -------------------------------------------------------------------------------- 1 | // An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y. 2 | // Given an integer n, return the largest number that is less than or equal to n with monotone increasing digits. 3 | // Example 1: 4 | // Input: n = 10 5 | // Output: 9 6 | // Example 2: 7 | // Input: n = 1234 8 | // Output: 1234 9 | // Example 3: 10 | // Input: n = 332 11 | // Output: 299 12 | 13 | // Constraints: 14 | // 0 <= n <= 109 15 | 16 | class Solution { 17 | public: 18 | int monotoneIncreasingDigits(int n) { 19 | string num = to_string(n); 20 | int monotoneIncreasingEnd = num.size() - 1, len = num.size(); 21 | for(int i = len - 1; i > 0; i--){ 22 | if(num[i-1] > num[i]){ 23 | monotoneIncreasingEnd = i-1; 24 | num[i-1]--; 25 | } 26 | } 27 | for(int i = monotoneIncreasingEnd + 1; i < len; i++) 28 | num[i] = '9'; 29 | return stoi(num); 30 | } 31 | }; -------------------------------------------------------------------------------- /Math/MonotoneIncreasingDigits738.java: -------------------------------------------------------------------------------- 1 | // An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y. 2 | // Given an integer n, return the largest number that is less than or equal to n with monotone increasing digits. 3 | // Example 1: 4 | // Input: n = 10 5 | // Output: 9 6 | // Example 2: 7 | // Input: n = 1234 8 | // Output: 1234 9 | // Example 3: 10 | // Input: n = 332 11 | // Output: 299 12 | 13 | // Constraints: 14 | // 0 <= n <= 109 15 | 16 | class Solution { 17 | public int monotoneIncreasingDigits(int N) { 18 | char[] arr = String.valueOf(N).toCharArray(); 19 | int monotoneIncreasingEnd = arr.length - 1, n = arr.length; 20 | for(int i = n - 1; i > 0; i--){ 21 | if(arr[i] < arr[i - 1]){ 22 | monotoneIncreasingEnd = i - 1; 23 | arr[i - 1]--; 24 | } 25 | } 26 | for(int i = monotoneIncreasingEnd + 1; i < n; i++) 27 | arr[i] = '9'; 28 | return Integer.parseInt(new String(arr)); 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /Math/Number Theory/CountPrimes204.cpp: -------------------------------------------------------------------------------- 1 | // 204. Count Primes 2 | 3 | // Count the number of prime numbers less than a non-negative number, n. 4 | 5 | // Example 1: 6 | 7 | // Input: n = 10 8 | // Output: 4 9 | // Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. 10 | // Example 2: 11 | 12 | // Input: n = 0 13 | // Output: 0 14 | // Example 3: 15 | 16 | // Input: n = 1 17 | // Output: 0 18 | 19 | 20 | // This uses sieve of eratosthenes for optimization 21 | class Solution { 22 | public: 23 | int countPrimes(int n) { 24 | if(n <= 1) return 0; 25 | vector primes(n, 1); 26 | primes[0] = primes[1] = 0; 27 | for(int i = 2; i*i < n; i++){ 28 | if(primes[i]){ 29 | for(int j = i; j*i < n; j++){ 30 | primes[i*j] = 0; 31 | } 32 | } 33 | } 34 | int count = 0; 35 | for(int i = 2; i < n; i++) 36 | if(primes[i]) 37 | count++; 38 | return count; 39 | } 40 | }; -------------------------------------------------------------------------------- /Math/Number Theory/CountPrimes204.java: -------------------------------------------------------------------------------- 1 | // 204. Count Primes 2 | 3 | // Count the number of prime numbers less than a non-negative number, n. 4 | 5 | // Example 1: 6 | 7 | // Input: n = 10 8 | // Output: 4 9 | // Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. 10 | // Example 2: 11 | 12 | // Input: n = 0 13 | // Output: 0 14 | // Example 3: 15 | 16 | // Input: n = 1 17 | // Output: 0 18 | 19 | 20 | // This uses sieve of eratosthenes for optimization 21 | 22 | class Solution { 23 | public int countPrimes(int n) { 24 | if(n <= 1) return 0; 25 | int[] primes = new int[n]; 26 | int count = 0; 27 | primes[0] = primes[1] = 0; 28 | for(int i = 2; i < n; i++) 29 | primes[i] = 1; 30 | for(int i = 2; i*i < n; i++){ 31 | if(primes[i] == 1){ 32 | for(int j = i; j*i < n; j++) 33 | primes[j*i] = 0; 34 | } 35 | } 36 | for(int i = 2; i < n; i++) 37 | if(primes[i] == 1) 38 | count++; 39 | return count; 40 | } 41 | } -------------------------------------------------------------------------------- /Math/PalindromeNumber9.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer x, return true if x is palindrome integer. 2 | // An integer is a palindrome when it reads the same backward as forward. 3 | // For example, 121 is palindrome while 123 is not. 4 | 5 | // Example 1: 6 | // Input: x = 121 7 | // Output: true 8 | // Example 2: 9 | // Input: x = -121 10 | // Output: false 11 | // Explanation: From left to right, it reads -121. From right to left, it becomes 121-. 12 | // Therefore it is not a palindrome. 13 | // Example 3: 14 | // Input: x = 10 15 | // Output: false 16 | // Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 17 | // Example 4: 18 | // Input: x = -101 19 | // Output: false 20 | 21 | // Constraints: 22 | // -231 <= x <= 231 - 1 23 | // Follow up: Could you solve it without converting the integer to a string? 24 | 25 | class Solution { 26 | public: 27 | bool isPalindrome(int x) { 28 | if(x == 0) return true; 29 | if(x < 0 or (x != 0 and x % 10 == 0)) return false; 30 | int sum = 0; 31 | while(x > sum){ 32 | sum = sum*10 + x % 10; 33 | x /= 10; 34 | } 35 | return (sum == x or x == sum/10); 36 | } 37 | }; -------------------------------------------------------------------------------- /Math/PalindromeNumber9.java: -------------------------------------------------------------------------------- 1 | // Given an integer x, return true if x is palindrome integer. 2 | // An integer is a palindrome when it reads the same backward as forward. 3 | // For example, 121 is palindrome while 123 is not. 4 | 5 | // Example 1: 6 | // Input: x = 121 7 | // Output: true 8 | // Example 2: 9 | // Input: x = -121 10 | // Output: false 11 | // Explanation: From left to right, it reads -121. From right to left, it becomes 121-. 12 | // Therefore it is not a palindrome. 13 | // Example 3: 14 | // Input: x = 10 15 | // Output: false 16 | // Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 17 | // Example 4: 18 | // Input: x = -101 19 | // Output: false 20 | 21 | // Constraints: 22 | // -231 <= x <= 231 - 1 23 | // Follow up: Could you solve it without converting the integer to a string? 24 | 25 | class Solution { 26 | public boolean isPalindrome(int x) { 27 | if(x == 0) return true; 28 | if(x < 0 || (x != 0 && x % 10 == 0)) return false; 29 | int sum = 0; 30 | while(x > sum){ 31 | sum = sum * 10 + (x % 10); 32 | x /= 10; 33 | } 34 | return (x == sum || ( x == sum / 10)); 35 | } 36 | } -------------------------------------------------------------------------------- /Math/Power-of-3.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer n, return true if it is a power of three. Otherwise, return false. 2 | 3 | // An integer n is a power of three, if there exists an integer x such that n == 3x. 4 | 5 | // Example 1: 6 | 7 | // Input: n = 27 8 | // Output: true 9 | // Example 2: 10 | 11 | // Input: n = 0 12 | // Output: false 13 | // Example 3: 14 | 15 | // Input: n = 9 16 | // Output: true 17 | // Example 4: 18 | 19 | // Input: n = 45 20 | // Output: false 21 | 22 | class Solution { 23 | public: 24 | bool isPowerOfThree(int n) { 25 | if(n<=0) return false; 26 | double x = log10(n)/log10(3); 27 | return x == int(x); 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Math/Powx-N-50.cpp: -------------------------------------------------------------------------------- 1 | // Implement pow(x, n), which calculates x raised to the power n (i.e., xn). 2 | 3 | // Example 1: 4 | 5 | // Input: x = 2.00000, n = 10 6 | // Output: 1024.00000 7 | // Example 2: 8 | 9 | // Input: x = 2.10000, n = 3 10 | // Output: 9.26100 11 | // Example 3: 12 | 13 | // Input: x = 2.00000, n = -2 14 | // Output: 0.25000 15 | // Explanation: 2-2 = 1/22 = 1/4 = 0.25 16 | 17 | 18 | // Constraints: 19 | 20 | // -100.0 < x < 100.0 21 | // -231 <= n <= 231-1 22 | // -104 <= xn <= 104 23 | 24 | class Solution { 25 | public: 26 | double myPow(double x, int n) { 27 | if(n == 0) 28 | return 1; 29 | if(n<0){ 30 | return 1/x * myPow(1/x, -(n + 1)); 31 | } 32 | return (n%2 == 0) ? myPow(x*x, n/2) : x*myPow(x*x, n/2); 33 | } 34 | }; -------------------------------------------------------------------------------- /Math/Powx-N-50.java: -------------------------------------------------------------------------------- 1 | // Implement pow(x, n), which calculates x raised to the power n (i.e., xn). 2 | // Example 1: 3 | // Input: x = 2.00000, n = 10 4 | // Output: 1024.00000 5 | // Example 2: 6 | 7 | // Input: x = 2.10000, n = 3 8 | // Output: 9.26100 9 | // Example 3: 10 | 11 | // Input: x = 2.00000, n = -2 12 | // Output: 0.25000 13 | // Explanation: 2-2 = 1/22 = 1/4 = 0.25 14 | 15 | 16 | // Constraints: 17 | 18 | // -100.0 < x < 100.0 19 | // -231 <= n <= 231-1 20 | // -104 <= xn <= 104 21 | 22 | 23 | class Solution { 24 | public double myPow(double x, int n) { 25 | if (n == 0) return 1; 26 | if (n < 0){ 27 | x = 1/x; 28 | return (n % 2 == 0) ? myPow(x*x, -(n/2)) : x*myPow(x*x, -(n/2)); 29 | } 30 | return (n %2 == 0) ? myPow(x*x, n/2) : x*myPow(x*x, n/2); 31 | } 32 | } -------------------------------------------------------------------------------- /Math/fizz-buzz.py: -------------------------------------------------------------------------------- 1 | # Given an integer n, return a string array answer (1-indexed) where: 2 | 3 | # answer[i] == "FizzBuzz" if i is divisible by 3 and 5. 4 | # answer[i] == "Fizz" if i is divisible by 3. 5 | # answer[i] == "Buzz" if i is divisible by 5. 6 | # answer[i] == i if non of the above conditions are true. 7 | 8 | 9 | # Example 1: 10 | 11 | # Input: n = 3 12 | # Output: ["1","2","Fizz"] 13 | # Example 2: 14 | 15 | # Input: n = 5 16 | # Output: ["1","2","Fizz","4","Buzz"] 17 | # Example 3: 18 | 19 | # Input: n = 15 20 | # Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"] 21 | 22 | class Solution: 23 | def fizzBuzz(self, n: int) -> List[str]: 24 | ans = [] 25 | for i in range(1, n+1): 26 | if i==1 or i ==2: 27 | ans.append(str(i)) 28 | elif i%3==0 and i%5==0: 29 | ans.append("FizzBuzz") 30 | elif i%3 == 0: 31 | ans.append("Fizz") 32 | elif i%5==0: 33 | ans.append("Buzz") 34 | else: 35 | ans.append(str(i)) 36 | return ans 37 | -------------------------------------------------------------------------------- /Math/perfect-squares.py: -------------------------------------------------------------------------------- 1 | # Given an integer n, return the least number of perfect square numbers that sum to n. 2 | 3 | # A perfect square is an integer that is the square of an integer; in other words, 4 | # it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not. 5 | 6 | # Example 1: 7 | 8 | # Input: n = 12 9 | # Output: 3 10 | # Explanation: 12 = 4 + 4 + 4. 11 | # Example 2: 12 | 13 | # Input: n = 13 14 | # Output: 2 15 | # Explanation: 13 = 4 + 9. 16 | 17 | class Solution: 18 | def numSquares(self, n: int) -> int: 19 | arr = [i for i in range(n+1)] 20 | for i in range(1, n+1): 21 | j = 1 22 | while(i - (j*j) >= 0 and (j*j) <= i): 23 | arr[i] = min(arr[i], 1 + arr[i-(j*j)]) 24 | j += 1 25 | return arr[-1] 26 | -------------------------------------------------------------------------------- /Math/ugly-number.cpp: -------------------------------------------------------------------------------- 1 | // An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. 2 | 3 | // Given an integer n, return true if n is an ugly number. 4 | 5 | // Example 1: 6 | 7 | // Input: n = 6 8 | // Output: true 9 | // Explanation: 6 = 2 × 3 10 | // Example 2: 11 | 12 | // Input: n = 8 13 | // Output: true 14 | // Explanation: 8 = 2 × 2 × 2 15 | // Example 3: 16 | 17 | // Input: n = 14 18 | // Output: false 19 | // Explanation: 14 is not ugly since it includes the prime factor 7. 20 | // Example 4: 21 | 22 | // Input: n = 1 23 | // Output: true 24 | // Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. 25 | 26 | 27 | class Solution { 28 | public: 29 | bool isUgly(int n) { 30 | if(n==0) return false; 31 | while(n%2==0) n/=2; 32 | while(n%3==0) n/=3; 33 | while(n%5==0) n/=5; 34 | return(n==1); 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Matrix/CountNegativeNumbersInASortedMatrix1351.cpp: -------------------------------------------------------------------------------- 1 | // Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, 2 | // return the number of negative numbers in grid. 3 | 4 | // Example 1: 5 | // Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] 6 | // Output: 8 7 | // Explanation: There are 8 negatives number in the matrix. 8 | // Example 2: 9 | // Input: grid = [[3,2],[1,0]] 10 | // Output: 0 11 | // Example 3: 12 | // Input: grid = [[1,-1],[-1,-1]] 13 | // Output: 3 14 | // Example 4: 15 | // Input: grid = [[-1]] 16 | // Output: 1 17 | 18 | // Constraints: 19 | // m == grid.length 20 | // n == grid[i].length 21 | // 1 <= m, n <= 100 22 | // -100 <= grid[i][j] <= 100 23 | 24 | class Solution { 25 | public: 26 | int countNegatives(vector>& grid) { 27 | int n = grid.size(), m = grid[0].size(), r = n-1, c = 0, count = 0; 28 | while(r >= 0 and c < m){ 29 | if(grid[r][c] < 0){ 30 | --r; 31 | count += m - c; 32 | } 33 | else ++c; 34 | } 35 | return count; 36 | } 37 | }; -------------------------------------------------------------------------------- /Matrix/CountNegativeNumbersInASortedMatrix1351.java: -------------------------------------------------------------------------------- 1 | // Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, 2 | // return the number of negative numbers in grid. 3 | 4 | // Example 1: 5 | // Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] 6 | // Output: 8 7 | // Explanation: There are 8 negatives number in the matrix. 8 | // Example 2: 9 | // Input: grid = [[3,2],[1,0]] 10 | // Output: 0 11 | // Example 3: 12 | // Input: grid = [[1,-1],[-1,-1]] 13 | // Output: 3 14 | // Example 4: 15 | // Input: grid = [[-1]] 16 | // Output: 1 17 | 18 | // Constraints: 19 | // m == grid.length 20 | // n == grid[i].length 21 | // 1 <= m, n <= 100 22 | // -100 <= grid[i][j] <= 100 23 | 24 | class Solution { 25 | public int countNegatives(int[][] grid) { 26 | int n = grid.length, m = grid[0].length, r = n - 1, c = 0, count = 0; 27 | while(r >= 0 && c < m){ 28 | if(grid[r][c] < 0){ 29 | --r; 30 | count += m - c; 31 | } 32 | else ++c; 33 | } 34 | return count; 35 | } 36 | } -------------------------------------------------------------------------------- /Matrix/Spiral-Matrix-2-59.cpp: -------------------------------------------------------------------------------- 1 | // Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. 2 | // Example 1: 3 | // Input: n = 3 4 | // Output: [[1,2,3],[8,9,4],[7,6,5]] 5 | // Example 2: 6 | // Input: n = 1 7 | // Output: [[1]] 8 | 9 | // Constraints: 10 | 11 | // 1 <= n <= 20 12 | 13 | class Solution { 14 | public: 15 | vector> generateMatrix(int n) { 16 | vector> res(n, vector(n,1)); 17 | int top = 0, bottom = n-1, left = 0, right = n-1, ind = 0; 18 | while(top<=bottom and left<=right){ 19 | for(int i=left; i<=right; i++) 20 | res[top][i] = ++ind; 21 | top++; 22 | 23 | for(int i=top; i<=bottom; i++) 24 | res[i][right] = ++ind; 25 | right--; 26 | 27 | for(int i=right; i>=left; i--) 28 | res[bottom][i] = ++ind; 29 | bottom--; 30 | 31 | for(int i=bottom; i>=top; i--) 32 | res[i][left] = ++ind; 33 | left++; 34 | } 35 | return res; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Object-Oriented Design/Singleton.java: -------------------------------------------------------------------------------- 1 | // Singleton is a most widely used design pattern. If a class has and only has one instance at every moment, 2 | // we call this design as singleton. For example, for class Mouse (not a animal mouse), we should design it 3 | // in singleton. 4 | // You job is to implement a getInstance method for given class, return the same instance of this class every 5 | // time you call this method. 6 | // Example 7 | // In Java: 8 | // A a = A.getInstance(); 9 | // A b = A.getInstance(); 10 | // a should equal to b. 11 | // Challenge 12 | // If we call getInstance concurrently, can you make sure your code could run correctly? 13 | 14 | class Solution { 15 | /** 16 | * @return: The same instance of this class every time 17 | */ 18 | 19 | private Solution(){ 20 | 21 | } 22 | 23 | private static class InstanceHolder{ 24 | private final static Solution INSTANCE = new Solution(); 25 | } 26 | 27 | public static Solution getInstance() { 28 | return InstanceHolder.INSTANCE; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Queues/ImplementQueueUsingArray.java: -------------------------------------------------------------------------------- 1 | class MyQueue { 2 | 3 | int front, rear; 4 | int arr[] = new int[100005]; 5 | 6 | MyQueue() 7 | { 8 | front=0; 9 | rear=0; 10 | } 11 | 12 | void push(int x) 13 | { 14 | if(rear >= 100000) 15 | return; 16 | arr[rear++] = x; 17 | } 18 | 19 | //Function to pop an element from queue and return that element. 20 | int pop() 21 | { 22 | return front == rear ? -1 : arr[front++]; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Queues/ImplementQueueUsingStacks.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devangi2000/Data-Structures-Algorithms-Handbook/127615e814dc3a53e25e01be86fadab458050ec0/Queues/ImplementQueueUsingStacks.cpp -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data-Structures-Algorithms-Handbook 2 | 3 | ### Ace that coding interview! 4 | A series of 500+ questions with solutions not only to crack that coding interview, but also ace it! 5 | Most of the solutions are in C++ but I shall constantly update the repository with solutions in C++ as well as Java. Will try to include Brute-Better-Optimal approaches in each question too. 6 | 7 | Here's a comprehensive list of resources I used during my coding interview prep - 8 | 9 | ## CompanyWise Questions: 10 | 11 | https://github.com/krishnadey30/LeetCode-Questions-CompanyWise 12 | 13 | ### Must do LC Questions: 14 | 15 | https://leetcode.com/discuss/career/452354/compilation-of-questions-covering-each-interview-question-pattern 16 | 17 | ## 450 DSA Sheet by Love Babbar: 18 | 19 | https://450dsa.com/ 20 | 21 | ## InterviewBit: 22 | 23 | https://www.interviewbit.com/coding-interview-questions/ 24 | 25 | ## Striver's SDE Sheet 26 | 27 | https://docs.google.com/document/d/1SM92efk8oDl8nyVw8NHPnbGexTS9W-1gmTEYfEurLWQ/preview?pru=AAABe4a-PVo*kDBTLY2GWFDjMGGGJ4-wxg# 28 | -------------------------------------------------------------------------------- /Sliding-Window/BinarySubarraysWithSum930.cpp: -------------------------------------------------------------------------------- 1 | // Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal. 2 | // A subarray is a contiguous part of the array. 3 | 4 | // Example 1: 5 | // Input: nums = [1,0,1,0,1], goal = 2 6 | // Output: 4 7 | // Explanation: The 4 subarrays are bolded and underlined below: 8 | // [1,0,1,0,1] 9 | // [1,0,1,0,1] 10 | // [1,0,1,0,1] 11 | // [1,0,1,0,1] 12 | // Example 2: 13 | // Input: nums = [0,0,0,0,0], goal = 0 14 | // Output: 15 15 | 16 | // Constraints: 17 | // 1 <= nums.length <= 3 * 104 18 | // nums[i] is either 0 or 1. 19 | // 0 <= goal <= nums.length 20 | 21 | class Solution { 22 | public: 23 | int numSubarraysWithSum(vector& nums, int goal) { 24 | int count = 0, sum = 0; 25 | unordered_map m; 26 | for(int i = 0; i < nums.size(); i++){ 27 | sum += nums[i]; 28 | if(m.find(sum - goal) != m.end()) 29 | count += m[sum - goal]; 30 | if(sum == goal) count++; 31 | m[sum]++; 32 | } 33 | return count; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Sliding-Window/BinarySubarraysWithSum930.java: -------------------------------------------------------------------------------- 1 | // Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal. 2 | // A subarray is a contiguous part of the array. 3 | 4 | // Example 1: 5 | // Input: nums = [1,0,1,0,1], goal = 2 6 | // Output: 4 7 | // Explanation: The 4 subarrays are bolded and underlined below: 8 | // [1,0,1,0,1] 9 | // [1,0,1,0,1] 10 | // [1,0,1,0,1] 11 | // [1,0,1,0,1] 12 | // Example 2: 13 | // Input: nums = [0,0,0,0,0], goal = 0 14 | // Output: 15 15 | 16 | // Constraints: 17 | // 1 <= nums.length <= 3 * 104 18 | // nums[i] is either 0 or 1. 19 | // 0 <= goal <= nums.length 20 | 21 | class Solution { 22 | public int numSubarraysWithSum(int[] nums, int goal) { 23 | Map mp = new HashMap<>(); 24 | int sum = 0, total = 0; 25 | for(int num : nums){ 26 | sum += num; 27 | if(mp.containsKey(sum - goal)) 28 | total += mp.get(sum - goal); 29 | if(sum == goal) total++; 30 | mp.put(sum, mp.getOrDefault(sum, 0) + 1); 31 | } 32 | return total; 33 | } 34 | } 35 | 36 | -------------------------------------------------------------------------------- /Sliding-Window/ContainsDuplicate2-219.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the 2 | // array such that nums[i] == nums[j] and abs(i - j) <= k. 3 | 4 | // Example 1: 5 | // Input: nums = [1,2,3,1], k = 3 6 | // Output: true 7 | // Example 2: 8 | // Input: nums = [1,0,1,1], k = 1 9 | // Output: true 10 | // Example 3: 11 | // Input: nums = [1,2,3,1,2,3], k = 2 12 | // Output: false 13 | 14 | // Constraints: 15 | // 1 <= nums.length <= 105 16 | // -109 <= nums[i] <= 109 17 | // 0 <= k <= 105 18 | 19 | class Solution { 20 | public: 21 | bool containsNearbyDuplicate(vector& nums, int k) { 22 | unordered_set s; 23 | for(int i = 0; i < nums.size(); ++i){ 24 | if(i > k) s.erase(nums[i-k-1]); 25 | if(s.find(nums[i]) != s.end()) return true; 26 | s.insert(nums[i]); 27 | } 28 | return false; 29 | } 30 | }; -------------------------------------------------------------------------------- /Sliding-Window/ContainsDuplicate2-219.java: -------------------------------------------------------------------------------- 1 | // Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the 2 | // array such that nums[i] == nums[j] and abs(i - j) <= k. 3 | 4 | // Example 1: 5 | // Input: nums = [1,2,3,1], k = 3 6 | // Output: true 7 | // Example 2: 8 | // Input: nums = [1,0,1,1], k = 1 9 | // Output: true 10 | // Example 3: 11 | // Input: nums = [1,2,3,1,2,3], k = 2 12 | // Output: false 13 | 14 | // Constraints: 15 | // 1 <= nums.length <= 105 16 | // -109 <= nums[i] <= 109 17 | // 0 <= k <= 105 18 | 19 | class Solution { 20 | public boolean containsNearbyDuplicate(int[] nums, int k) { 21 | Set set = new HashSet<>(); 22 | for(int i = 0; i < nums.length; i++){ 23 | if(i > k) set.remove(nums[i-k-1]); 24 | if(!set.add(nums[i])) return true; 25 | } 26 | return false; 27 | } 28 | } -------------------------------------------------------------------------------- /Sliding-Window/ContiguousArray525.java: -------------------------------------------------------------------------------- 1 | // Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1. 2 | // Example 1: 3 | // Input: nums = [0,1] 4 | // Output: 2 5 | // Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1. 6 | // Example 2: 7 | // Input: nums = [0,1,0] 8 | // Output: 2 9 | // Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. 10 | 11 | // Constraints: 12 | // 1 <= nums.length <= 105 13 | // nums[i] is either 0 or 1. 14 | 15 | class Solution { 16 | public int findMaxLength(int[] nums) { 17 | int maxi = 0, sum = 0; 18 | Map mp = new HashMap<>(); 19 | for(int i = 0; i < nums.length; i++){ 20 | sum += (nums[i] == 0 ? -1 : 1); 21 | if(sum == 0) maxi = Math.max(maxi, i + 1); 22 | else if(mp.containsKey(sum)){ 23 | maxi = Math.max(maxi, i - mp.get(sum)); 24 | } 25 | else mp.put(sum, i); 26 | } 27 | return maxi; 28 | } 29 | } -------------------------------------------------------------------------------- /Sliding-Window/LongestSubstringWithAtMostKDistinctCharacters.cpp: -------------------------------------------------------------------------------- 1 | // Given a string S, find the length of the longest substring T that contains at most k distinct characters. 2 | // Example 3 | // Example 1: 4 | // Input: S = "eceba" and k = 3 5 | // Output: 4 6 | // Explanation: T = "eceb" 7 | // Example 2: 8 | // Input: S = "WORLD" and k = 4 9 | // Output: 4 10 | // Explanation: T = "WORL" or "ORLD" 11 | // Challenge 12 | // O(n) time 13 | 14 | class Solution { 15 | public: 16 | 17 | int lengthOfLongestSubstringKDistinct(string &s, int k) { 18 | int maxlen = INT_MIN, left = 0, right = 0, n = s.length(); 19 | if(n == 0 || k == 0) return 0; 20 | unordered_map m; 21 | while(right < n){ 22 | m[s[right++]]++; 23 | while(m.size() > k){ 24 | m[s[left]]--; 25 | if(m[s[left]] == 0) 26 | m.erase(s[left]); 27 | left++; 28 | } 29 | maxlen = max(maxlen, right - left); 30 | } 31 | return maxlen; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Sliding-Window/LongestSubstringWithAtMostKDistinctCharacters.java: -------------------------------------------------------------------------------- 1 | // Given a string S, find the length of the longest substring T that contains at most k distinct characters. 2 | // Example 3 | // Example 1: 4 | // Input: S = "eceba" and k = 3 5 | // Output: 4 6 | // Explanation: T = "eceb" 7 | // Example 2: 8 | // Input: S = "WORLD" and k = 4 9 | // Output: 4 10 | // Explanation: T = "WORL" or "ORLD" 11 | // Challenge 12 | // O(n) time 13 | 14 | public class Solution { 15 | public int lengthOfLongestSubstringKDistinct(String s, int k) { 16 | int n = s.length(), left = 0, right = 0, maxlen = Integer.MIN_VALUE, count = 0; 17 | if(n == 0 || k == 0) return 0; 18 | int[] mp = new int[256]; 19 | while(right < n){ 20 | if(mp[s.charAt(right)] == 0) ++count; 21 | mp[s.charAt(right)]++; 22 | right++; 23 | while(count > k){ 24 | mp[s.charAt(left)]--; 25 | if(mp[s.charAt(left)]== 0) 26 | --count; 27 | left++; 28 | } 29 | maxlen = Math.max(maxlen, right - left); 30 | } 31 | 32 | return maxlen; 33 | } 34 | } -------------------------------------------------------------------------------- /Sliding-Window/LongestSubstringWithAtMostTwoDistinctCharacters.cpp: -------------------------------------------------------------------------------- 1 | // Given a string, find the length of the longest substring T that contains at most 2 distinct characters. 2 | // Example 3 | // Example 1 4 | // Input: “eceba” 5 | // Output: 3 6 | // Explanation: 7 | // T is "ece" which its length is 3. 8 | // Example 2 9 | // Input: “aaa” 10 | // Output: 3 11 | 12 | class Solution { 13 | public: 14 | 15 | int lengthOfLongestSubstringTwoDistinct(string &s) { 16 | int left = 0, right = 0, maxlen = INT_MIN, n = s.length(); 17 | if(n == 0) return 0; 18 | unordered_map m; 19 | while(right < n){ 20 | m[s[right++]]++; 21 | while(m.size() > 2){ 22 | m[s[left]]--; 23 | if(m[s[left]] == 0) 24 | m.erase(s[left]); 25 | left++; 26 | } 27 | maxlen = max(maxlen, right - left); 28 | } 29 | return maxlen; 30 | } 31 | }; -------------------------------------------------------------------------------- /Sliding-Window/LongestSubstringWithAtMostTwoDistinctCharacters.java: -------------------------------------------------------------------------------- 1 | // Given a string, find the length of the longest substring T that contains at most 2 distinct characters. 2 | // Example 3 | // Example 1 4 | // Input: “eceba” 5 | // Output: 3 6 | // Explanation: 7 | // T is "ece" which its length is 3. 8 | // Example 2 9 | // Input: “aaa” 10 | // Output: 3 11 | 12 | public class Solution { 13 | 14 | public int lengthOfLongestSubstringTwoDistinct(String s) { 15 | int left = 0, right = 0, maxlen = Integer.MIN_VALUE, n = s.length(), count = 0; 16 | if(n == 0) return 0; 17 | int[] m = new int[256]; 18 | while(right < n){ 19 | if(m[s.charAt(right)] == 0) count++; 20 | m[s.charAt(right)]++; 21 | right++; 22 | while(count > 2){ 23 | m[s.charAt(left)]--; 24 | if(m[s.charAt(left)] == 0) 25 | count--; 26 | left++; 27 | } 28 | maxlen = Math.max(maxlen, right - left); 29 | } 30 | return maxlen; 31 | } 32 | } -------------------------------------------------------------------------------- /Sliding-Window/SUbarrayWithKDifferentIntegers992.java: -------------------------------------------------------------------------------- 1 | // Given an integer array nums and an integer k, return the number of good subarrays of nums. 2 | // A good array is an array where the number of different integers in that array is exactly k. 3 | // For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3. 4 | // A subarray is a contiguous part of an array. 5 | 6 | // Example 1: 7 | // Input: nums = [1,2,1,2,3], k = 2 8 | // Output: 7 9 | // Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2] 10 | // Example 2: 11 | // Input: nums = [1,2,1,3,4], k = 3 12 | // Output: 3 13 | // Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4]. 14 | 15 | // Constraints: 16 | // 1 <= nums.length <= 2 * 104 17 | // 1 <= nums[i], k <= nums.length 18 | 19 | -------------------------------------------------------------------------------- /Sliding-Window/Smallest-Subarray-with-Sum-Greater-than-K.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/smallest-subarray-with-sum-greater-than-x5651/1 2 | 3 | // A[] = {1, 4, 45, 6, 0, 19} 4 | // x = 51 5 | // Output: 3 6 | // Explanation: 7 | // Minimum length subarray is 8 | // {4, 45, 6} 9 | 10 | // Example 2: 11 | // Input: 12 | // A[] = {1, 10, 5, 2, 7} 13 | // x = 9 14 | // Output: 1 15 | // Explanation: 16 | // Minimum length subarray is {10} 17 | // Expected Time Complexity: O(N) 18 | // Expected Auxiliary Space: O(1) 19 | 20 | // Constraints: 21 | // 1 ≤ N, x ≤ 105 22 | // 1 ≤ A[] ≤ 104 23 | 24 | class Solution{ 25 | public: 26 | int sb(int arr[], int n, int x) 27 | { 28 | int ans = INT_MAX, start = 0, end = 0, sum = 0; 29 | while(end x and start < n){ 36 | ans = min(ans, end - start); 37 | sum -= arr[start]; 38 | start++; 39 | } 40 | } 41 | return ans; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Sliding-Window/SubarrayProductLessThanK713.cpp: -------------------------------------------------------------------------------- 1 | // Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k. 2 | 3 | 4 | 5 | // Example 1: 6 | 7 | // Input: nums = [10,5,2,6], k = 100 8 | // Output: 8 9 | // Explanation: The 8 subarrays that have product less than 100 are: 10 | // [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6] 11 | // Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k. 12 | // Example 2: 13 | 14 | // Input: nums = [1,2,3], k = 0 15 | // Output: 0 16 | 17 | 18 | // Constraints: 19 | 20 | // 1 <= nums.length <= 3 * 104 21 | // 1 <= nums[i] <= 1000 22 | // 0 <= k <= 106 23 | 24 | class Solution { 25 | public: 26 | int numSubarrayProductLessThanK(vector& nums, int k) { 27 | if(k<=1) return 0; 28 | int left = 0, right = 0, prod = 1, result = 0; 29 | while(right=k){ 32 | prod /= nums[left]; 33 | left++; 34 | } 35 | result += right-left+1; 36 | right++; 37 | } 38 | return result; 39 | } 40 | }; -------------------------------------------------------------------------------- /Sliding-Window/SubarrayProductLessThanK713.java: -------------------------------------------------------------------------------- 1 | // Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k. 2 | 3 | 4 | 5 | // Example 1: 6 | 7 | // Input: nums = [10,5,2,6], k = 100 8 | // Output: 8 9 | // Explanation: The 8 subarrays that have product less than 100 are: 10 | // [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6] 11 | // Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k. 12 | // Example 2: 13 | 14 | // Input: nums = [1,2,3], k = 0 15 | // Output: 0 16 | 17 | 18 | // Constraints: 19 | 20 | // 1 <= nums.length <= 3 * 104 21 | // 1 <= nums[i] <= 1000 22 | // 0 <= k <= 106 23 | 24 | class Solution { 25 | public int numSubarrayProductLessThanK(int[] nums, int k) { 26 | int n = nums.length, left = 0, right = 0, pro = 1, count = 0; 27 | if(k <= 1) return 0; 28 | while(right < n){ 29 | pro *= nums[right]; 30 | while(pro >= k){ 31 | pro /= nums[left++]; 32 | } 33 | count += right - left + 1; 34 | right++; 35 | } 36 | return count; 37 | } 38 | } 39 | 40 | -------------------------------------------------------------------------------- /Stacks/132Pattern456.cpp: -------------------------------------------------------------------------------- 1 | // Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] 2 | // and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j]. 3 | // Return true if there is a 132 pattern in nums, otherwise, return false. 4 | 5 | // Example 1: 6 | // Input: nums = [1,2,3,4] 7 | // Output: false 8 | // Explanation: There is no 132 pattern in the sequence. 9 | // Example 2: 10 | // Input: nums = [3,1,4,2] 11 | // Output: true 12 | // Explanation: There is a 132 pattern in the sequence: [1, 4, 2]. 13 | // Example 3: 14 | // Input: nums = [-1,3,2,0] 15 | // Output: true 16 | // Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. 17 | // Constraints: 18 | // n == nums.length 19 | // 1 <= n <= 2 * 105 20 | // -109 <= nums[i] <= 109 21 | 22 | -------------------------------------------------------------------------------- /Stacks/DailyTemperatures739.java: -------------------------------------------------------------------------------- 1 | // Given an array of integers temperatures represents the daily temperatures, 2 | // return an array answer such that answer[i] is the number of days you have to 3 | // wait after the ith day to get a warmer temperature. If there is no future day 4 | // for which this is possible, keep answer[i] == 0 instead. 5 | 6 | // Example 1: 7 | 8 | // Input: temperatures = [73,74,75,71,69,72,76,73] 9 | // Output: [1,1,4,2,1,1,0,0] 10 | // Example 2: 11 | 12 | // Input: temperatures = [30,40,50,60] 13 | // Output: [1,1,1,0] 14 | // Example 3: 15 | 16 | // Input: temperatures = [30,60,90] 17 | // Output: [1,1,0] 18 | 19 | // Constraints: 20 | 21 | // 1 <= temperatures.length <= 105 22 | // 30 <= temperatures[i] <= 100 23 | 24 | class Solution { 25 | public int[] dailyTemperatures(int[] temps) { 26 | Stack st = new Stack<>(); 27 | int[] ans = new int[temps.length]; 28 | for(int i = temps.length - 1; i >= 0; i--){ 29 | while(!st.isEmpty() && temps[st.peek()] <= temps[i]) 30 | st.pop(); 31 | ans[i] = st.empty() ? 0 : st.peek() - i; 32 | st.push(i); 33 | } 34 | return ans; 35 | } 36 | } -------------------------------------------------------------------------------- /Stacks/Longest-Valid-Parentheses-32.cpp: -------------------------------------------------------------------------------- 1 | // Given a string containing just the characters '(' and ')', find the 2 | // length of the longest valid (well-formed) parentheses substring. 3 | 4 | // Example 1: 5 | 6 | // Input: s = "(()" 7 | // Output: 2 8 | // Explanation: The longest valid parentheses substring is "()". 9 | // Example 2: 10 | 11 | // Input: s = ")()())" 12 | // Output: 4 13 | // Explanation: The longest valid parentheses substring is "()()". 14 | // Example 3: 15 | 16 | // Input: s = "" 17 | // Output: 0 18 | // Constraints: 19 | 20 | // 0 <= s.length <= 3 * 104 21 | // s[i] is '(', or ')'. 22 | 23 | class Solution { 24 | public: 25 | stack st; 26 | int ans = 0; 27 | int longestValidParentheses(string s){ 28 | int n = s.size(); 29 | st.push(-1); 30 | for(int i=0; i st; 29 | st.push(0); 30 | for(auto c : s){ 31 | if(c == '(') 32 | st.push(0); 33 | else{ 34 | int u = st.top(); st.pop(); 35 | int v = st.top(); st.pop(); 36 | st.push(v + max(2*u, 1)); 37 | } 38 | } 39 | return st.top(); 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Stacks/ScoreOfParentheses856.java: -------------------------------------------------------------------------------- 1 | // Given a balanced parentheses string s, return the score of the string. 2 | // The score of a balanced parentheses string is based on the following rule: 3 | // "()" has score 1. 4 | // AB has score A + B, where A and B are balanced parentheses strings. 5 | // (A) has score 2 * A, where A is a balanced parentheses string. 6 | 7 | // Example 1: 8 | // Input: s = "()" 9 | // Output: 1 10 | // Example 2: 11 | // Input: s = "(())" 12 | // Output: 2 13 | // Example 3: 14 | // Input: s = "()()" 15 | // Output: 2 16 | // Example 4: 17 | // Input: s = "(()(()))" 18 | // Output: 6 19 | 20 | // Constraints: 21 | // 2 <= s.length <= 50 22 | // s consists of only '(' and ')'. 23 | // s is a balanced parentheses string. 24 | 25 | class Solution { 26 | public int scoreOfParentheses(String s) { 27 | Stack st = new Stack(); 28 | st.push(0); 29 | for(char c : s.toCharArray()){ 30 | if(c == '(') 31 | st.push(0); 32 | else{ 33 | int u = st.pop(); 34 | int v = st.pop(); 35 | st.push(v + Math.max(1, 2*u)); 36 | } 37 | } 38 | return st.pop(); 39 | } 40 | } -------------------------------------------------------------------------------- /Strings/ConsecutiveCharacters1446.java: -------------------------------------------------------------------------------- 1 | // The power of the string is the maximum length of a non-empty substring that contains only one unique 2 | // character. 3 | // Given a string s, return the power of s. 4 | 5 | // Example 1: 6 | // Input: s = "leetcode" 7 | // Output: 2 8 | // Explanation: The substring "ee" is of length 2 with the character 'e' only. 9 | // Example 2: 10 | // Input: s = "abbcccddddeeeeedcba" 11 | // Output: 5 12 | // Explanation: The substring "eeeee" is of length 5 with the character 'e' only. 13 | // Example 3: 14 | // Input: s = "triplepillooooow" 15 | // Output: 5 16 | // Example 4: 17 | // Input: s = "hooraaaaaaaaaaay" 18 | // Output: 11 19 | // Example 5: 20 | // Input: s = "tourist" 21 | // Output: 1 22 | 23 | // Constraints: 24 | // 1 <= s.length <= 500 25 | // s consists of only lowercase English letters. 26 | 27 | class Solution { 28 | public int maxPower(String s) { 29 | int count = 0, maxi = 1; 30 | char prev = s.charAt(0); 31 | for(char c : s.toCharArray()){ 32 | if(c == prev) ++count; 33 | else count = 1; 34 | prev = c; 35 | maxi = Math.max(maxi, count); 36 | } 37 | return maxi; 38 | } 39 | } -------------------------------------------------------------------------------- /Strings/DetectCapital520.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool detectCapitalUse(string word) { 4 | int n = word.size(); 5 | if(n == 1) return true; 6 | if(isupper(word[0]) && isupper(word[1])){ 7 | for(int i = 2; i < n; i++) 8 | if(islower(word[i]))return false; 9 | } else if(isupper(word[0]) && islower(word[1])) { 10 | for(int i = 2; i < n; i++) 11 | if(isupper(word[i])) return false; 12 | } 13 | else if(islower(word[0])) 14 | for(int i = 0; i < n; i++) 15 | if(isupper(word[i])) return false; 16 | return true; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Strings/Largest-Number-179.cpp: -------------------------------------------------------------------------------- 1 | // Given a list of non-negative integers nums, arrange them such that they form the largest number. 2 | // Note: The result may be very large, so you need to return a string instead of an integer. 3 | 4 | // Example 1: 5 | 6 | // Input: nums = [10,2] 7 | // Output: "210" 8 | // Example 2: 9 | 10 | // Input: nums = [3,30,34,5,9] 11 | // Output: "9534330" 12 | // Example 3: 13 | 14 | // Input: nums = [1] 15 | // Output: "1" 16 | // Example 4: 17 | 18 | // Input: nums = [10] 19 | // Output: "10" 20 | 21 | // Constraints: 22 | 23 | // 1 <= nums.length <= 100 24 | // 0 <= nums[i] <= 109 25 | 26 | class Solution { 27 | public: 28 | static bool compare(string a, string b){ 29 | return b+a < a+b; 30 | } 31 | string largestNumber(vector& nums){ 32 | vector v; 33 | for(auto num : nums) 34 | v.push_back(to_string(num)); 35 | sort(v.begin(), v.end(), compare); 36 | string res = ""; 37 | for(auto num: v) 38 | res += num; 39 | while(res[0]=='0' && res.length()>1) 40 | res.erase(0,1); 41 | return res; 42 | } 43 | }; -------------------------------------------------------------------------------- /Strings/LengthOfLastWord58.cpp: -------------------------------------------------------------------------------- 1 | // Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string. 2 | // A word is a maximal substring consisting of non-space characters only. 3 | // Example 1: 4 | // Input: s = "Hello World" 5 | // Output: 5 6 | // Explanation: The last word is "World" with length 5. 7 | // Example 2: 8 | // Input: s = " fly me to the moon " 9 | // Output: 4 10 | // Explanation: The last word is "moon" with length 4. 11 | // Example 3: 12 | // Input: s = "luffy is still joyboy" 13 | // Output: 6 14 | // Explanation: The last word is "joyboy" with length 6. 15 | 16 | // Constraints: 17 | // 1 <= s.length <= 104 18 | // s consists of only English letters and spaces ' '. 19 | // There will be at least one word in s. 20 | 21 | class Solution { 22 | public: 23 | int lengthOfLastWord(string s) { 24 | int len = 0, n = s.size()-1; 25 | while(n >= 0 and s[n] == ' ') n--; 26 | while(n >= 0 and s[n--] != ' ') len++; 27 | return len; 28 | } 29 | }; -------------------------------------------------------------------------------- /Strings/LengthOfLastWord58.java: -------------------------------------------------------------------------------- 1 | // Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string. 2 | // A word is a maximal substring consisting of non-space characters only. 3 | // Example 1: 4 | // Input: s = "Hello World" 5 | // Output: 5 6 | // Explanation: The last word is "World" with length 5. 7 | // Example 2: 8 | // Input: s = " fly me to the moon " 9 | // Output: 4 10 | // Explanation: The last word is "moon" with length 4. 11 | // Example 3: 12 | // Input: s = "luffy is still joyboy" 13 | // Output: 6 14 | // Explanation: The last word is "joyboy" with length 6. 15 | 16 | // Constraints: 17 | // 1 <= s.length <= 104 18 | // s consists of only English letters and spaces ' '. 19 | // There will be at least one word in s. 20 | 21 | class Solution { 22 | public int lengthOfLastWord(String s) { 23 | int n = s.length() - 1, len = 0; 24 | while(n >= 0 && s.charAt(n) == ' ') n--; 25 | while(n >= 0 && s.charAt(n--) != ' ') len++; 26 | return len; 27 | } 28 | } -------------------------------------------------------------------------------- /Strings/RansomNote383.cpp: -------------------------------------------------------------------------------- 1 | // Given two stings ransomNote and magazine, return true if ransomNote can be constructed from magazine 2 | // and false otherwise. 3 | // Each letter in magazine can only be used once in ransomNote. 4 | 5 | // Example 1: 6 | // Input: ransomNote = "a", magazine = "b" 7 | // Output: false 8 | // Example 2: 9 | // Input: ransomNote = "aa", magazine = "ab" 10 | // Output: false 11 | // Example 3: 12 | // Input: ransomNote = "aa", magazine = "aab" 13 | // Output: true 14 | 15 | // Constraints: 16 | // 1 <= ransomNote.length, magazine.length <= 105 17 | // ransomNote and magazine consist of lowercase English letters. 18 | 19 | class Solution { 20 | public: 21 | bool canConstruct(string ransomNote, string magazine) { 22 | vector chars(26, 0); 23 | for(char c : magazine) 24 | chars[c-'a']++; 25 | for(char c : ransomNote){ 26 | if(--chars[c-'a'] < 0) 27 | return false; 28 | } 29 | return true; 30 | } 31 | }; -------------------------------------------------------------------------------- /Strings/RansomNote383.java: -------------------------------------------------------------------------------- 1 | // Given two stings ransomNote and magazine, return true if ransomNote can be constructed from magazine 2 | // and false otherwise. 3 | // Each letter in magazine can only be used once in ransomNote. 4 | 5 | // Example 1: 6 | // Input: ransomNote = "a", magazine = "b" 7 | // Output: false 8 | // Example 2: 9 | // Input: ransomNote = "aa", magazine = "ab" 10 | // Output: false 11 | // Example 3: 12 | // Input: ransomNote = "aa", magazine = "aab" 13 | // Output: true 14 | 15 | // Constraints: 16 | // 1 <= ransomNote.length, magazine.length <= 105 17 | // ransomNote and magazine consist of lowercase English letters. 18 | 19 | class Solution { 20 | public boolean canConstruct(String ransomNote, String magazine) { 21 | int[] chars = new int[26]; 22 | for(Character c : magazine.toCharArray()) 23 | chars[c-'a']++; 24 | for(Character c : ransomNote.toCharArray()){ 25 | if(--chars[c-'a'] < 0) 26 | return false; 27 | } 28 | return true; 29 | } 30 | } -------------------------------------------------------------------------------- /Strings/ReverseWordsInAString3-557.cpp: -------------------------------------------------------------------------------- 1 | // Given a string s, reverse the order of characters in each word within a sentence while still preserving 2 | // whitespace and initial word order. 3 | 4 | // Example 1: 5 | // Input: s = "Let's take LeetCode contest" 6 | // Output: "s'teL ekat edoCteeL tsetnoc" 7 | // Example 2: 8 | // Input: s = "God Ding" 9 | // Output: "doG gniD" 10 | 11 | // Constraints: 12 | // 1 <= s.length <= 5 * 104 13 | // s contains printable ASCII characters. 14 | // s does not contain any leading or trailing spaces. 15 | // There is at least one word in s. 16 | // All the words in s are separated by a single space. 17 | 18 | class Solution { 19 | public: 20 | string reverseWords(string s) { 21 | string res = ""; 22 | for(int i = 0; i < s.length(); i++){ 23 | if(s[i] != ' '){ 24 | int j = i; 25 | for(; j < s.length() and s[j] != ' '; j++){} 26 | reverse(s.begin() + i, s.begin() + j); 27 | i = j - 1; 28 | } 29 | } 30 | return s; 31 | } 32 | }; -------------------------------------------------------------------------------- /Strings/ReverseWordsInAString3-557.java: -------------------------------------------------------------------------------- 1 | // Given a string s, reverse the order of characters in each word within a sentence while still preserving 2 | // whitespace and initial word order. 3 | 4 | // Example 1: 5 | // Input: s = "Let's take LeetCode contest" 6 | // Output: "s'teL ekat edoCteeL tsetnoc" 7 | // Example 2: 8 | // Input: s = "God Ding" 9 | // Output: "doG gniD" 10 | 11 | // Constraints: 12 | // 1 <= s.length <= 5 * 104 13 | // s contains printable ASCII characters. 14 | // s does not contain any leading or trailing spaces. 15 | // There is at least one word in s. 16 | // All the words in s are separated by a single space. 17 | 18 | class Solution { 19 | public String reverseWords(String s) { 20 | String words[] = s.split(" "); 21 | StringBuilder sb = new StringBuilder(); 22 | for(String word : words){ 23 | sb.append(new StringBuffer(word).reverse().toString() + " "); 24 | } 25 | return sb.toString().trim(); 26 | } 27 | } -------------------------------------------------------------------------------- /Strings/RotateString796.cpp: -------------------------------------------------------------------------------- 1 | // Given two strings s and goal, return true if and only if s can become goal after 2 | // some number of shifts on s. 3 | // A shift on s consists of moving the leftmost character of s to the rightmost position. 4 | // For example, if s = "abcde", then it will be "bcdea" after one shift. 5 | 6 | // Example 1: 7 | // Input: s = "abcde", goal = "cdeab" 8 | // Output: true 9 | // Example 2: 10 | // Input: s = "abcde", goal = "abced" 11 | // Output: false 12 | 13 | // Constraints: 14 | // 1 <= s.length, goal.length <= 100 15 | // s and goal consist of lowercase English letters. 16 | 17 | class Solution { 18 | public: 19 | bool rotateString(string s, string goal) { 20 | return s.size() == goal.size() && (s + s).find(goal) != string::npos; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Strings/RotateString796.java: -------------------------------------------------------------------------------- 1 | // Given two strings s and goal, return true if and only if s can become goal after 2 | // some number of shifts on s. 3 | // A shift on s consists of moving the leftmost character of s to the rightmost position. 4 | // For example, if s = "abcde", then it will be "bcdea" after one shift. 5 | 6 | // Example 1: 7 | // Input: s = "abcde", goal = "cdeab" 8 | // Output: true 9 | // Example 2: 10 | // Input: s = "abcde", goal = "abced" 11 | // Output: false 12 | 13 | // Constraints: 14 | // 1 <= s.length, goal.length <= 100 15 | // s and goal consist of lowercase English letters. 16 | 17 | class Solution { 18 | public boolean rotateString(String s, String goal) { 19 | return s.length() == goal.length() && (s + s).contains(goal); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Strings/first-unique-character-in-string.cpp: -------------------------------------------------------------------------------- 1 | // Given a string s, return the first non-repeating character in it and return its index. If it does not exist, return -1. 2 | 3 | 4 | 5 | // Example 1: 6 | 7 | // Input: s = "leetcode" 8 | // Output: 0 9 | // Example 2: 10 | 11 | // Input: s = "loveleetcode" 12 | // Output: 2 13 | // Example 3: 14 | 15 | // Input: s = "aabb" 16 | // Output: -1 17 | 18 | class Solution { 19 | public: 20 | int firstUniqChar(string s) { 21 | unordered_map m; 22 | for(auto a:s) m[a]++; 23 | for(int i=0; i str: 17 | if len(strs) == 0: return "" 18 | if len(strs) == 1: return strs[0] 19 | 20 | prefix = strs[0] 21 | ans = len(prefix) 22 | for s in strs[1:]: 23 | while(prefix !=s[:ans]): 24 | ans -= 1 25 | prefix = prefix[:ans] 26 | return prefix 27 | -------------------------------------------------------------------------------- /Strings/valid-anagram.cpp: -------------------------------------------------------------------------------- 1 | // Given two strings s and t, return true if t is an anagram of s, and false otherwise. 2 | 3 | 4 | 5 | // Example 1: 6 | 7 | // Input: s = "anagram", t = "nagaram" 8 | // Output: true 9 | // Example 2: 10 | 11 | // Input: s = "rat", t = "car" 12 | // Output: false 13 | 14 | 15 | // Constraints: 16 | 17 | // 1 <= s.length, t.length <= 5 * 104 18 | // s and t consist of lowercase English letters. 19 | 20 | class Solution { 21 | public: 22 | bool isAnagram(string s, string t) { 23 | unordered_map m; 24 | if(s.size() != t.size()) return false; 25 | for(auto a : s) m[a]++; 26 | for(auto a: t) 27 | { 28 | if(m.find(a) == m.end()){ 29 | return false; 30 | } 31 | else if(m.find(a)!=m.end()) 32 | { 33 | m[a]--; 34 | if(m[a]<0) return false; 35 | } 36 | else continue; 37 | } 38 | return true; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Strings/valid-palindrome.py: -------------------------------------------------------------------------------- 1 | # Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 2 | 3 | 4 | 5 | # Example 1: 6 | 7 | # Input: s = "A man, a plan, a canal: Panama" 8 | # Output: true 9 | # Explanation: "amanaplanacanalpanama" is a palindrome. 10 | # Example 2: 11 | 12 | # Input: s = "race a car" 13 | # Output: false 14 | # Explanation: "raceacar" is not a palindrome. 15 | 16 | 17 | # Constraints: 18 | 19 | # 1 <= s.length <= 2 * 105 20 | # s consists only of printable ASCII characters. 21 | 22 | 23 | class Solution: 24 | def isPalindrome(self, s: str) -> bool: 25 | s1 = '' 26 | for i in s: 27 | if i.isalnum(): 28 | s1 += i.lower() 29 | sr = '' 30 | for i in reversed(s1): 31 | sr += i 32 | 33 | if(s1==sr): return True 34 | return False 35 | -------------------------------------------------------------------------------- /Trees/Binary-Tree-Level-Order-Traversal-102.cpp: -------------------------------------------------------------------------------- 1 | // Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). 2 | 3 | // Example 1: 4 | // Input: root = [3,9,20,null,null,15,7] 5 | // Output: [[3],[9,20],[15,7]] 6 | // Example 2: 7 | 8 | // Input: root = [1] 9 | // Output: [[1]] 10 | // Example 3: 11 | 12 | // Input: root = [] 13 | // Output: [] 14 | 15 | // Constraints: 16 | 17 | // The number of nodes in the tree is in the range [0, 2000]. 18 | // -1000 <= Node.val <= 1000 19 | 20 | class Solution { 21 | public: 22 | vector> ans; 23 | queue q; 24 | vector> levelOrder(TreeNode* root){ 25 | if(!root) return ans; 26 | q.push(root); 27 | while(!q.empty()){ 28 | vector v; 29 | int n = q.size(); 30 | for(int i=0; ival); 34 | if(temp->left) q.push(temp->left); 35 | if(temp->right) q.push(temp->right); 36 | } 37 | ans.push_back(v); 38 | } 39 | return ans; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Trees/Flatten-Binary-Tree-to-Linked-List-114.java: -------------------------------------------------------------------------------- 1 | // Given the root of a binary tree, flatten the tree into a "linked list": 2 | // The "linked list" should use the same TreeNode class where the right child pointer points 3 | // to the next node in the list and the left child pointer is always null. 4 | // The "linked list" should be in the same order as a pre-order traversal of the binary tree. 5 | 6 | // Example 1: 7 | // Input: root = [1,2,5,3,4,null,6] 8 | // Output: [1,null,2,null,3,null,4,null,5,null,6] 9 | // Example 2: 10 | // Input: root = [] 11 | // Output: [] 12 | // Example 3: 13 | // Input: root = [0] 14 | // Output: [0] 15 | // Constraints: 16 | // The number of nodes in the tree is in the range [0, 2000]. 17 | // -100 <= Node.val <= 100 18 | 19 | // Follow up: Can you flatten the tree in-place (with O(1) extra space)? -------------------------------------------------------------------------------- /Trees/HeightOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | // Given a binary tree, find its height. 2 | 3 | 4 | // Example 1: 5 | 6 | // Input: 7 | // 1 8 | // / \ 9 | // 2 3 10 | // Output: 2 11 | // Example 2: 12 | 13 | // Input: 14 | // 2 15 | // \ 16 | // 1 17 | // / 18 | // 3 19 | // Output: 3 20 | 21 | // Your Task: 22 | // You don't need to read input or print anything. Your task is to complete the function height() which takes root node of the tree as input parameter and returns an integer denoting the height of the tree. If the tree is empty, return 0. 23 | 24 | 25 | // Expected Time Complexity: O(N) 26 | // Expected Auxiliary Space: O(N) 27 | 28 | 29 | // Constraints: 30 | // 1 <= Number of nodes <= 105 31 | // 1 <= Data of a node <= 105 32 | 33 | /* 34 | class Node 35 | { 36 | int data; 37 | Node left, right; 38 | 39 | Node(int item) 40 | { 41 | data = item; 42 | left = right = null; 43 | } 44 | } 45 | */ 46 | 47 | class Solution { 48 | int height(Node root) 49 | { 50 | if(root == null) return 0; 51 | int left = height(root.left); 52 | int right = height(root.right); 53 | return 1 + Math.max(left, right); 54 | } 55 | } -------------------------------------------------------------------------------- /Trees/Invert-Binary-Tree-226.cpp: -------------------------------------------------------------------------------- 1 | // Given the root of a binary tree, invert the tree, and return its root. 2 | 3 | // Example 1: 4 | 5 | // Input: root = [4,2,7,1,3,6,9] 6 | // Output: [4,7,2,9,6,3,1] 7 | // Example 2: 8 | 9 | 10 | // Input: root = [2,1,3] 11 | // Output: [2,3,1] 12 | // Example 3: 13 | 14 | // Input: root = [] 15 | // Output: [] 16 | 17 | // Constraints: 18 | 19 | // The number of nodes in the tree is in the range [0, 100]. 20 | // -100 <= Node.val <= 100 21 | 22 | class Solution { 23 | public: 24 | TreeNode* invertTree(TreeNode* root) { 25 | if(!root) return NULL; 26 | invertTree(root->left); 27 | invertTree(root->right); 28 | swap(root->left, root->right); 29 | return root; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Trees/Invert-Binary-Tree-226.java: -------------------------------------------------------------------------------- 1 | // Given the root of a binary tree, invert the tree, and return its root. 2 | 3 | // Example 1: 4 | 5 | // Input: root = [4,2,7,1,3,6,9] 6 | // Output: [4,7,2,9,6,3,1] 7 | // Example 2: 8 | 9 | 10 | // Input: root = [2,1,3] 11 | // Output: [2,3,1] 12 | // Example 3: 13 | 14 | // Input: root = [] 15 | // Output: [] 16 | 17 | // Constraints: 18 | 19 | // The number of nodes in the tree is in the range [0, 100]. 20 | // -100 <= Node.val <= 100 21 | /** 22 | * Definition for a binary tree node. 23 | * public class TreeNode { 24 | * int val; 25 | * TreeNode left; 26 | * TreeNode right; 27 | * TreeNode() {} 28 | * TreeNode(int val) { this.val = val; } 29 | * TreeNode(int val, TreeNode left, TreeNode right) { 30 | * this.val = val; 31 | * this.left = left; 32 | * this.right = right; 33 | * } 34 | * } 35 | */ 36 | class Solution { 37 | public TreeNode invertTree(TreeNode root) { 38 | if(root == null) 39 | return root; 40 | TreeNode temp = root.left; 41 | root.left = invertTree(root.right); 42 | root.right = invertTree(temp); 43 | return root; 44 | } 45 | } -------------------------------------------------------------------------------- /Trees/LowestCommonAncestor236.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devangi2000/Data-Structures-Algorithms-Handbook/127615e814dc3a53e25e01be86fadab458050ec0/Trees/LowestCommonAncestor236.java -------------------------------------------------------------------------------- /Two Pointers/ContainerWithMostWater11.cpp: -------------------------------------------------------------------------------- 1 | // You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). 2 | 3 | // Find two lines that together with the x-axis form a container, such that the container contains the most water. 4 | 5 | // Return the maximum amount of water a container can store. 6 | 7 | // Notice that you may not slant the container. 8 | 9 | 10 | 11 | // Example 1: 12 | 13 | 14 | // Input: height = [1,8,6,2,5,4,8,3,7] 15 | // Output: 49 16 | // Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. 17 | 18 | 19 | class Solution { 20 | public: 21 | int maxArea(vector& height) { 22 | int area = INT_MIN, i = 0, j = height.size() - 1; 23 | while(i < j){ 24 | int mini = min(height[i], height[j]); 25 | area = max(area, mini * (j - i)); 26 | if(height[i] < height[j]) i++; 27 | else j--; 28 | } 29 | return area == INT_MIN ? 0 : area; 30 | } 31 | }; -------------------------------------------------------------------------------- /Two Pointers/ContainerWithMostWater11.java: -------------------------------------------------------------------------------- 1 | // You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). 2 | 3 | // Find two lines that together with the x-axis form a container, such that the container contains the most water. 4 | 5 | // Return the maximum amount of water a container can store. 6 | 7 | // Notice that you may not slant the container. 8 | 9 | 10 | 11 | // Example 1: 12 | 13 | 14 | // Input: height = [1,8,6,2,5,4,8,3,7] 15 | // Output: 49 16 | // Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. 17 | 18 | 19 | class Solution { 20 | public int maxArea(int[] height) { 21 | int area = Integer.MIN_VALUE, i = 0, j = height.length - 1; 22 | while(i < j){ 23 | int mini = Math.min(height[i], height[j]); 24 | area = Math.max(area, mini * (j - i)); 25 | if(height[i] < height[j]) i++; 26 | else j--; 27 | } 28 | return area == Integer.MIN_VALUE ? 0 : area; 29 | } 30 | } -------------------------------------------------------------------------------- /Two Pointers/IntersectionOfTwoSortedArrays.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::intersect(const vector &A, const vector &B) { 2 | int i = 0, j = 0; 3 | vector ans; 4 | while(i < A.size() and j < B.size()){ 5 | if(A[i] == B[j]){ 6 | ans.push_back(A[i]); 7 | i++; j++; 8 | } 9 | else if(A[i] < B[j]) i++; 10 | else j++; 11 | } 12 | return ans; 13 | } -------------------------------------------------------------------------------- /Two Pointers/IntersectionOfTwoSortedArrays.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | // DO NOT MODIFY THE LIST. IT IS READ ONLY 3 | public ArrayList intersect(final List A, final List B) { 4 | ArrayList ans = new ArrayList(); 5 | int i = 0, j = 0; 6 | while(i < A.size() && j < B.size()){ 7 | if(A.get(i) == B.get(j)){ 8 | ans.add(A.get(i)); 9 | i++; j++; 10 | } 11 | else if(A.get(i) < B.get(j)) i++; 12 | else j++; 13 | } 14 | return ans; 15 | } 16 | } -------------------------------------------------------------------------------- /Two Pointers/MoveZeroes283.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero 2 | // elements. 3 | // Note that you must do this in-place without making a copy of the array. 4 | 5 | // Example 1: 6 | // Input: nums = [0,1,0,3,12] 7 | // Output: [1,3,12,0,0] 8 | // Example 2: 9 | // Input: nums = [0] 10 | // Output: [0] 11 | 12 | // Constraints: 13 | // 1 <= nums.length <= 104 14 | // -231 <= nums[i] <= 231 - 1 15 | 16 | // Follow up: Could you minimize the total number of operations done? 17 | 18 | using namespace std; 19 | class Solution { 20 | public: 21 | void moveZeroes(vector& nums) { 22 | int n = nums.size(), j = 0, zeroes = 0; 23 | for(int i = 0; i < n; i++){ 24 | if(nums[i] == 0){ 25 | zeroes++; 26 | } 27 | else nums[j++] = nums[i]; 28 | } 29 | while(zeroes--) 30 | nums[j++] = 0; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Two Pointers/MoveZeroes283.java: -------------------------------------------------------------------------------- 1 | // Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero 2 | // elements. 3 | // Note that you must do this in-place without making a copy of the array. 4 | 5 | // Example 1: 6 | // Input: nums = [0,1,0,3,12] 7 | // Output: [1,3,12,0,0] 8 | // Example 2: 9 | // Input: nums = [0] 10 | // Output: [0] 11 | 12 | // Constraints: 13 | // 1 <= nums.length <= 104 14 | // -231 <= nums[i] <= 231 - 1 15 | 16 | // Follow up: Could you minimize the total number of operations done? 17 | 18 | class Solution { 19 | public void moveZeroes(int[] nums) { 20 | int n = nums.length, j = 0, zeroes = 0; 21 | for(int i = 0; i < n; i++){ 22 | if(nums[i] == 0){ 23 | zeroes++; 24 | } 25 | else nums[j++] = nums[i]; 26 | } 27 | while(zeroes>0){ 28 | nums[j++] = 0; 29 | zeroes--; 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /Two Pointers/MoveZeroes283.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. 3 | 4 | Note that you must do this in-place without making a copy of the array. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: nums = [0,1,0,3,12] 11 | Output: [1,3,12,0,0] 12 | Example 2: 13 | 14 | Input: nums = [0] 15 | Output: [0] 16 | 17 | 18 | Constraints: 19 | 20 | 1 <= nums.length <= 104 21 | -231 <= nums[i] <= 231 - 1 22 | 23 | 24 | Follow up: Could you minimize the total number of operations done? 25 | """ 26 | 27 | 28 | class Solution: 29 | def moveZeroes(self, nums: List[int]) -> None: 30 | """ 31 | Do not return anything, modify nums in-place instead. 32 | """ 33 | n = len(nums) 34 | j, z = 0, 0 35 | for num in nums: 36 | if num!=0: 37 | nums[j] = num 38 | j+=1 39 | else: z+=1 40 | for i in range(z): 41 | nums[j] = 0 42 | j += 1 43 | return nums 44 | -------------------------------------------------------------------------------- /Two Pointers/Remove-Nth-Node-From-End-of-List-19.cpp: -------------------------------------------------------------------------------- 1 | // Given the head of a linked list, remove the nth node from the end of the list and return its head. 2 | 3 | // Example 1: 4 | 5 | // Input: head = [1,2,3,4,5], n = 2 6 | // Output: [1,2,3,5] 7 | // Example 2: 8 | // Input: head = [1], n = 1 9 | // Output: [] 10 | // Example 3: 11 | // Input: head = [1,2], n = 1 12 | // Output: [1] 13 | 14 | // Constraints: 15 | // The number of nodes in the list is sz. 16 | // 1 <= sz <= 30 17 | // 0 <= Node.val <= 100 18 | // 1 <= n <= sz 19 | 20 | class Solution { 21 | public: 22 | ListNode* removeNthFromEnd(ListNode* head, int n){ 23 | ListNode *start = new ListNode(0, head); 24 | ListNode *slow = start, *fast = start; 25 | for(int i = 0; i < n; i++) 26 | fast = fast->next; 27 | while(fast and fast->next){ 28 | slow = slow->next; 29 | fast = fast->next; 30 | } 31 | slow->next = slow->next->next; 32 | return start->next; 33 | } 34 | }; -------------------------------------------------------------------------------- /Two Pointers/Trapping-Rain-Water-42.java: -------------------------------------------------------------------------------- 1 | // Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. 2 | 3 | // Example 1: 4 | 5 | // Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] 6 | // Output: 6 7 | // Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. 8 | // Example 2: 9 | 10 | // Input: height = [4,2,0,3,2,5] 11 | // Output: 9 12 | 13 | // Constraints: 14 | 15 | // n == height.length 16 | // 0 <= n <= 3 * 104 17 | // 0 <= height[i] <= 105 18 | 19 | class Solution { 20 | public int trap(int[] height) { 21 | int n = height.length, ans = 0; 22 | int[] left = new int[n]; 23 | left[0] = height[0]; 24 | for(int i = 1; i < n; i++) 25 | left[i] = Math.max(left[i-1], height[i]); 26 | int[] right = new int[n]; 27 | right[n-1] = height[n-1]; 28 | for(int i = n-2; i >= 0; i--) 29 | right[i] = Math.max(right[i+1], height[i]); 30 | for(int i = 0; i < n; i++) 31 | ans += Math.max(0, Math.min(left[i], right[i]) - height[i]); 32 | return ans; 33 | } 34 | } -------------------------------------------------------------------------------- /Union Find/AccountsMerge721.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devangi2000/Data-Structures-Algorithms-Handbook/127615e814dc3a53e25e01be86fadab458050ec0/Union Find/AccountsMerge721.cpp -------------------------------------------------------------------------------- /Union Find/AccountsMerge721.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devangi2000/Data-Structures-Algorithms-Handbook/127615e814dc3a53e25e01be86fadab458050ec0/Union Find/AccountsMerge721.java -------------------------------------------------------------------------------- /big-o-cheatsheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devangi2000/Data-Structures-Algorithms-Handbook/127615e814dc3a53e25e01be86fadab458050ec0/big-o-cheatsheet.pdf --------------------------------------------------------------------------------