├── Bitwise-operator.c ├── CONTRIBUTING.md ├── PARTICIPANTS.md ├── README.md ├── RULES.md ├── array-rever ├── bubble_sort.cpp ├── c ├── 1-Two-Sum.c ├── 100-Same-Tree.c ├── 104-Maximum-Depth-Of-Binary-Tree.c ├── 11-Container-With-Most-Water.c ├── 110-Balanced-Binary-Tree.c ├── 121-Best-Time-To-Buy-And-Sell-Stock.c ├── 124-Binary-Tree-Maximum-Path-Sum.c ├── 125-Valid-Palindrome.c ├── 130-Surrounded-Regions.c ├── 133-Clone-Graph.c ├── 134-Gas-Station.c ├── 136-Single-Number.c ├── 141-Linked-List-Cycle.c ├── 143-Reorder-List.c ├── 1448-Count-Good-Nodes-in-Binary-Tree.c ├── 152-Maximum-Product-Subarray.c ├── 153-Find-Minimum-in-Rotated-Sorted-Array.c ├── 167-Two-Sum-II.c ├── 19-Remove-Nth-Node-From-End-of-List.c ├── 190-Reverse-Bits.c ├── 191-Number-of-1-Bits.c ├── 198-House-Robber.c ├── 199-Binary-Tree-Right-Side-View.c ├── 2-Add-Two-Numbers.c ├── 20-Valid-Parentheses.c ├── 200-Number-Of-Islands.c ├── 202-Happy-Number.c ├── 206-Reverse-Linked-List.c ├── 208-Implement-Trie-Prefix-Tree.c ├── 21-Merge-Two-Sorted-Lists.c ├── 213-House-Robber-II.c ├── 217-Contains-Duplicate.c ├── 226-Invert-Binary-Tree.c ├── 235-Lowest-Common-Ancestor-Of-A-Binary-Search-Tree.c ├── 238-Product-of-Array-Except-Self.c ├── 242-Valid-Anagram.c ├── 268-Missing-Number.c ├── 287-Find-The-Duplicate-Number.c ├── 3-Longest-Substring-Without-Repeating-Characters.c ├── 300-Longest-Increasing-Subsequence.c ├── 309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.c ├── 322-Coin-Change.c ├── 329-Longest-Increasing-Path-in-a-Matrix.c ├── 33-Search-in-Rotated-Sorted-Array.c ├── 338-Counting-Bits.c ├── 36-Valid-Sudoku.c ├── 371-Sum-of-Two-Integers.c ├── 417-Pacific-Atlantic-Waterflow.c ├── 42-Trapping-Rain-Water.c ├── 424-Longest-Repeating-Character-Replacement.c ├── 45-Jump-Game-II.c ├── 48-Rotate-Image.c ├── 5-Longest-Palindromic-Substring.c ├── 50-Pow-X-N.c ├── 53-Maximum-Subarray.c ├── 543-Diameter-Of-Binary-Tree.c ├── 55-Jump-Game.c ├── 567-Permutation-in-String.c ├── 572-Subtree-Of-Another-Tree.c ├── 62-Unique-Paths.c ├── 647-Palindromic-Substrings.c ├── 66-Plus-One.c ├── 678-Valid-Parenthesis-String.c ├── 684-Redundant-Connection.c ├── 695-Max-Area-of-Island.c ├── 7-Reverse-Integer.c ├── 70-Climbing-Stairs.c ├── 703-Kth-Largest-Element-In-A-Stream.c ├── 704-Binary-Search.c ├── 73-Set-Matrix-Zeroes.c ├── 739-Daily-Temperatures.c ├── 74-Search-A-2D-Matrix.c ├── 746-Min-Cost-Climbing-Stairs.c ├── 76-Minimum-Window-Substring.c ├── 78-Subsets.c ├── 79-Word-Search.c ├── 84. Largest Rectangle in Histogram ├── 875-Koko-Eating-Bananas.c ├── 98-Validate-Binary-Search-Tree.c ├── 994-Rotting-Oranges.c └── Intersection_point-Linked-List.c ├── cpp ├── 1-Two-Sum.cpp ├── 10-Regular-Expression-Matching.cpp ├── 100-Same-Tree.cpp ├── 102-Binary-Tree-Level-Order-Traversal.cpp ├── 104-Maximum-Depth-Of-Binary-Tree.cpp ├── 1046-Last-Stone-Weight.cpp ├── 105-Construct-Binary-Tree-From-Preorder-And-Inorder.cpp ├── 11-Container-With-Most-Water.cpp ├── 110-Balanced-Binary-Tree.cpp ├── 1143-Longest-Common-Subsequence.cpp ├── 115-Distinct-Subsequences.cpp ├── 118_pascal_triangle.cpp ├── 120-Triangle.cpp ├── 121-Best-Time-To-Buy-And-Sell-Stock.cpp ├── 1213-Maximum-Product-Difference-Between-Two-Pairs.cpp ├── 124-Binary-Tree-Maximum-Path-Sum.cpp ├── 125-Valid-Palindrome.cpp ├── 127-Word-Ladder.cpp ├── 128-Longest-Consecutive-Sequence.cpp ├── 1299-Replace-Elements-with-Greatest-Element-on-Right-Side.cpp ├── 13-RomanToInt.cpp ├── 130-Surrounded-Regions.cpp ├── 131-Palindrome-Partitioning.cpp ├── 133-Clone-Graph.cpp ├── 134-Gas-Station.cpp ├── 136-Single-Number.cpp ├── 138-Copy-List-With-Random-Pointer.cpp ├── 139-Word-Break.cpp ├── 141-Linked-List-Cycle.cpp ├── 143-Reorder-List.cpp ├── 1448-Count-Good-Nodes-In-Binary-Tree.cpp ├── 146-Lru-Cache.cpp ├── 15-3sum.cpp ├── 150-Evaluate-Reverse-Polish-Notation.cpp ├── 1512-Number-Of-Good-Pairs.cpp ├── 152-Maximum-Product-Subarray.cpp ├── 153-Find-Minimum-In-Rotated-Sorted-Array.cpp ├── 155-Min-Stack.cpp ├── 1584-Min-Cost-To-Connect-All-Points.cpp ├── 167-Two-Sum-II.cpp ├── 17-Letter-Combinations-Phone-Number.cpp ├── 1851-Minimum-Interval-To-Include-Each-Query.cpp ├── 189-Rotate-Array.cpp ├── 1899-Merge-Triplets-To-Form-Target-Triplet.cpp ├── 19-Remove-Nth-Node-From-End-Of-List.cpp ├── 190-Reverse-Bits.cpp ├── 191-Number-Of-1-Bits.cpp ├── 1920-Build-Array-From-Permutation.cpp ├── 1929-Cocatenation-Of-Array.cpp ├── 198-House-Robber.cpp ├── 199-Binary-Tree-Right-Side-View.cpp ├── 2-Add-Two-Numbers.cpp ├── 20-Valid-Parentheses.cpp ├── 20-Valid-Parenthesis-String.cpp ├── 200-Number-Of-Islands.cpp ├── 2013-Detect-Squares.cpp ├── 202-Happy-Number.cpp ├── 2050-Parallel-Courses-III.cpp ├── 206-Reverse-Linked-List.cpp ├── 207-Course-Schedule.cpp ├── 208-Implement-Trie-Prefix-Tree.cpp ├── 209-Minimum-Size-Subarray-Sum.cpp ├── 21-Merge-Two-Sorted-Lists.cpp ├── 210-Course-Schedule-II.cpp ├── 211-Design-Add-And-Search-Words-Data-Structure.cpp ├── 212-Word-Search-II.cpp ├── 213-House-Robber-II.cpp ├── 2149. rearrange array elements by sign.cpp ├── 215-Kth-Largest-Element-In-Array.cpp ├── 217-Contains-Duplicate.cpp ├── 22-Generate-Parentheses.cpp ├── 222.Count Complete Tree.cpp ├── 2235-Add-Two-Integers.cpp ├── 226-Invert-Binary-Tree.cpp ├── 23-Merge-K-Sorted-Lists.cpp ├── 230-Kth-Smallest-Element-In-A-Bst.cpp ├── 230. Kth Smallest Element in a BST.cpp ├── 2315-Count-Asterisks.cpp ├── 234-Palindrome-Linked-List.cpp ├── 235-Lowest-Common-Ancestor-Of-A-Binary-Search-Tree.cpp ├── 236-Power-Of-Three.cpp ├── 2374-Node-With-Highest-Edge-Score.cpp ├── 238-Product-Of-Array-Except-Self.cpp ├── 239-Sliding-Window-Maximum.cpp ├── 242-Valid-Anagram-Hashmap.cpp ├── 242-Valid-Anagram.cpp ├── 2420-Find-all-good-indices.cpp ├── 2425. Bitwise XOR of All Pairings ├── 2433. Find The Original Array of Prefix Xor.cpp ├── 25-Reverse-Nodes-In-K-Group.cpp ├── 252-Meeting-Rooms.cpp ├── 253-Meeting-Rooms-II.cpp ├── 261-Graph-Valid-Tree.cpp ├── 268-Missing-Number.cpp ├── 269-Alien-Dictionary.cpp ├── 271-Encode-And-Decode-Strings.cpp ├── 278-First-Bad-Version.cpp ├── 286-Walls-And-Gates.cpp ├── 287-Find-The-Duplicate-Number.cpp ├── 295-Find-Median-From-Data-Stream.cpp ├── 297-Serialize-And-Deserialize-Binary-Tree.cpp ├── 299-Bull-and-Cows.cpp ├── 3-Longest-Substring-Without-Repeating-Characters.cpp ├── 300-Longest-Increasing-Subsequence.cpp ├── 309-Best-Time-To-Buy-And-Sell-Stock-With-Cooldown.cpp ├── 312-Burst-Balloons.cpp ├── 322-Coin-Change.cpp ├── 323-Number-Of-Connected-Components-In-An-Undirected-Graph.cpp ├── 326-Power_of_Three ├── 329-Longest-Increasing-Path-In-A-Matrix.cpp ├── 33-Search-In-Rotated-Sorted-Array.cpp ├── 332-Reconstruct-Itinerary.cpp ├── 334-Increasing-Triplet-Subsequence.cpp ├── 338-Counting-Bits.cpp ├── 342-Power-Of-Four.cpp ├── 347-Top-K-Frequent-Elements.cpp ├── 35-Search-Insert-Position.cpp ├── 355-Design-Twitter.cpp ├── 36-Valid-Sudoku.cpp ├── 371-Sum-Of-Two-Integers.cpp ├── 387-First-Unique-Character-In-A-String.cpp ├── 39-Combination-Sum.cpp ├── 392-Is-Subsequence.cpp ├── 3Sum_Closest.cpp ├── 4-Median-Of-Two-Sorted-Arrays.cpp ├── 40-Combination-Sum-II.cpp ├── 416-Partition-Equal-Subset-Sum.cpp ├── 417-Pacific-Atlantic-Water-Flow.cpp ├── 42-Trapping-Rain-Water.cpp ├── 424-Longest-Repeating-Character-Replacement.cpp ├── 43-Multiply-Strings.cpp ├── 435-Non-Overlapping-Intervals.cpp ├── 438-Find-All-Anagrams-In-A-String.cpp ├── 45-Jump-Game-II.cpp ├── 46-Permutations.cpp ├── 48-Rotate-Image.cpp ├── 49-Group-Anagrams.cpp ├── 494-Target-Sum.cpp ├── 5-Longest-Palindrome-Substring.cpp ├── 50-Pow-X-N.cpp ├── 51-N-Queens.cpp ├── 518-Coin-Change-2.cpp ├── 53-Maximum-Subarray.cpp ├── 54-Spiral-Matrix.cpp ├── 543-Diameter-Of-Binary-Tree.cpp ├── 55-Jump-Game.cpp ├── 56-Merge-Intervals.cpp ├── 567-Permutation-In-String.cpp ├── 57-Insert-Interval.cpp ├── 572-Subtree-Of-Another-Tree.cpp ├── 62-Unique-Paths.cpp ├── 621-Task-Scheduler.cpp ├── 64-Minimum-Path-Sum.cpp ├── 647-Palindromic-Substrings.cpp ├── 66-Plus-One.cpp ├── 678-Valid-Parenthesis-String.cpp ├── 684-Redundant-Connection.cpp ├── 695-Max-Area-Of-Island.cpp ├── 7-Reverse-Integer.cpp ├── 7. Reverse Integer.cpp ├── 70-Climbing-Stairs.cpp ├── 703-Kth-Largest-Element-In-A-Stream.cpp ├── 704-Binary-Search.cpp ├── 72-Edit-Distance.cpp ├── 73-Set-Matrix-Zeroes.cpp ├── 739-Daily-Temperatures.cpp ├── 74-Search-A-2d-Matrix.cpp ├── 743-Network-Delay-Time.cpp ├── 746-Min-Cost-Climbing-Stairs.cpp ├── 76-Minimum-Window-Substring.cpp ├── 763-Partition-Labels.cpp ├── 778-Swim-In-Rising-Water.cpp ├── 78-Subsets.cpp ├── 787-Cheapest-Flights-Within-K-Stops.cpp ├── 79-Word-Search.cpp ├── 84-Largest-Rectangle-In-Histogram.cpp ├── 846-Hand-Of-Straights.cpp ├── 853-Car-Fleet.cpp ├── 875-Koko-Eating-Bananas.cpp ├── 876-Middle-of-the-Linked-List.cpp ├── 90-Subsets-II.cpp ├── 91-Decode-Ways.cpp ├── 953-Alien-Dictionary.cpp ├── 97-Interleaving-String.cpp ├── 973-K-Closest-Points-To-Origin.cpp ├── 977-Squares-of-a-Sorted-Array.cpp ├── 98-Validate-Binary-Search-Tree.cpp ├── 981-Time-Based-Key-Value-Store.cpp ├── 994-Rotting-Oranges.cpp ├── BookAlocation.cpp ├── Merge_k_Sorted_Lists.cpp ├── PrintStars.cpp ├── SegmentTree(distinct-value-queries).cpp ├── Shuffle_String.cpp ├── Simplify_Path.cpp ├── approach2.cpp ├── basic.cpp ├── longsubtraction.cpp ├── maxelement.cpp ├── maximumPassengers.cpp ├── mergepull.cpp └── pathSum.cpp ├── csharp ├── 1-Two-Sum.cs ├── 10-Regular-Expression-Matching.cs ├── 100-Same-Tree.cs ├── 102-Binary-Tree-Level-Order-Traversal.cs ├── 104-Maximum-Depth-of-Binary-Tree.cs ├── 1046-Last-Stone-Weight.cs ├── 105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.cs ├── 1094-Car-Pooling.cs ├── 11-Container-With-Most-Water.cs ├── 110-Balanced-Binary-Tree.cs ├── 1143-Longest-Common-Subsequence.cs ├── 115-Distinct-Subsequences.cs ├── 121-Best-Time-To-Buy-and-Sell-Stock.cs ├── 124-Binary-Tree-Maximum-Path-Sum.cs ├── 125-Valid-Palindrome.cs ├── 127-Word-Ladder.cs ├── 128-Longest-Consecutive-Sequence.cs ├── 130-Surrounded-Regions.cs ├── 131-Palindrome-Partitioning.cs ├── 133-Clone-Graph.cs ├── 134-Gas-Station.cs ├── 136-Single-Number.cs ├── 138-Copy-List-With-Random-Pointer.cs ├── 1383-Maximum-Performance-Of-A-Team.cs ├── 139-Word-Break.cs ├── 141-Linked-List-Cycle.cs ├── 1423-Maximum-Points-You-Can-Obtain-from-Cards.cs ├── 143-Reorder-List.cs ├── 1448-Count-Good-Nodes-in-Binary-Tree.cs ├── 146-LRU-Cache.cs ├── 1466-Reorder-Routes-to-Make-All-Paths-Lead-To-The-City-Zero.cs ├── 1480-Running-Sum-Of-1D-Array.cs ├── 15-3Sum.cs ├── 150-Evaluate-Reverse-Polish-Notation.cs ├── 152-Maximum-Product-Subarray.cs ├── 153-Find-Minimum-in-Rotated-Sorted-Array.cs ├── 155-Min-Stack.cs ├── 1584-Min-Cost-to-Connect-All-Points.cs ├── 167-Two-Sum-II.cs ├── 17-Letter-Combinations-Of-A-Phone-Number.cs ├── 1851-Minimum-Interval-to-Include-Each-Query.cs ├── 1899-Merge-Triplets-to-Form-Target-Triplet.cs ├── 19-Remove-Nth-Node-From-End-of-List.cs ├── 190-Reverse-Bits.cs ├── 1905-Count-Sub-Islands.cs ├── 191-Number-Of-1-Bits.cs ├── 198-House-Robber.cs ├── 199-Binary-Tree-Right-Side-View.cs ├── 2-Add-Two-Numbers.cs ├── 20-Valid-Parentheses.cs ├── 200-Number-Of-Islands.cs ├── 2013-Detect-Squares.cs ├── 202-Happy-Number.cs ├── 206-Reverse-Linked-List.cs ├── 207-Course-Schedule.cs ├── 208-Implement-Trie.cs ├── 21-Merge-Two-Sorted-Lists.cs ├── 210-Course-Schedule-II.cs ├── 211-Design-Add-and-Search-Words-Data-Structure.cs ├── 212-Word-Search-II.cs ├── 213-House-Robber-II.cs ├── 215-Kth-Largest-Element-in-an-Array.cs ├── 217-Contains-Duplicate.cs ├── 22-Generate-Parentheses.cs ├── 226-Invert-Binary-Tree.cs ├── 23-Merge-K-Sorted-Lists.cs ├── 230-Kth-Smallest-Element-in-a-BST.cs ├── 235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.cs ├── 238-Product-Of-Array-Except-Self.cs ├── 239-Sliding-Window-Maximum.cs ├── 242-Valid-Anagram.cs ├── 25-Reverse-Nodes-in-k-Group.cs ├── 252-Meeting-Rooms.cs ├── 253-Meeting-Rooms-II.cs ├── 261-Graph-Valid-Tree.cs ├── 268-Missing-Number.cs ├── 269-Alien-Dictionary.cs ├── 271-Encode-And-Decode-Strings .cs ├── 286-Walls-and-Gates.cs ├── 287-Find-the-Duplicate-Number.cs ├── 295-Find-Median-From-Data-Stream.cs ├── 297-Serialize-and-Deserialize-Binary-Tree.cs ├── 3-Longest-Substring-Without-Repeating-Characters.cs ├── 300-Longest-Increasing-Subsequence.cs ├── 309-Best-Time-to-Buy-and-Sell-Stock-With-Cooldown.cs ├── 312-Burst-Balloons.cs ├── 315-Count-of-Smaller-Numbers-After-Self.cs ├── 322-Coin-Change.cs ├── 323-Number-Of-Connected-Components-In-An-Undirected-Graph.cs ├── 329-Longest-Increasing-Path-in-a-Matrix.cs ├── 33-Search-In-Rotated-Sorted-Array.cs ├── 332-Reconstruct-Itinerary.cs ├── 338-Counting-Bits.cs ├── 34-Find-First-and-Last-Position-of-Element-in-Sorted-Array.cs ├── 347-Top-K-Frequent-Elements.cs ├── 355-Design-Twitter.cs ├── 36-Valid-Sudoku.cs ├── 371-Sum-Of-Two-Integers.cs ├── 39-Combination-Sum.cs ├── 392-Is-Subsequence.cs ├── 4-Median-of-Two-Sorted-Arrays.cs ├── 40-Combination-Sum-II.cs ├── 416-Partition-Equal-Subset-Sum.cs ├── 417-Pacific-Atlantic-Water-Flow.cs ├── 42-Trapping-Rain-Water.cs ├── 424-Longest-Repeating-Character-Replacement.cs ├── 43-Multiply-Strings.cs ├── 435-Non-overlapping-Intervals.cs ├── 45-Jump-Game-II.cs ├── 46-Permutations.cs ├── 463-Island-Perimeter.cs ├── 48-Rotate-Image.cs ├── 49-Group-Anagrams.cs ├── 494-Target-Sum.cs ├── 5-Longest-Palindromic-Substring.cs ├── 50-Pow(x, n).cs ├── 51-N-Queens.cs ├── 518-Coin-Change-II.cs ├── 53-Maximum-Subarray.cs ├── 54-Spiral-Matrix.cs ├── 543-Diameter-of-Binary-Tree.cs ├── 55-Jump-Game.cs ├── 56-Merge-Intervals.cs ├── 567-Permutation-In-String.cs ├── 57-Insert-Interval.cs ├── 572-Subtree-of-Another-Tree.cs ├── 62-Unique-Paths.cs ├── 621-Task-Scheduler.cs ├── 647-Palindromic-Substrings.cs ├── 66-Plus-One.cs ├── 678-Valid-Parenthesis-String.cs ├── 684-Redundant-Connection.cs ├── 695-Max-Area-of-Island.cs ├── 7-Reverse-Integer.cs ├── 70-Climbing-Stairs.cs ├── 703-Kth-Largest-Element-In-A-Stream.cs ├── 704-Binary-Search.cs ├── 72-Edit-Distance.cs ├── 73-Set-Matrix-Zeroes.cs ├── 739-Daily-Temperatures.cs ├── 74-Search-A-2D-Matrix.cs ├── 743-Network-Delay-Time.cs ├── 746-Min-Cost-Climbing-Stairs.cs ├── 752-Open-the-Lock.cs ├── 76-Minimum-Window-Substring.cs ├── 763-Partition-Labels.cs ├── 778-Swim-in-Rising-Water.cs ├── 78-Subsets.cs ├── 787-Cheapest-Flights-Within-K-Stops.cs ├── 79-Word-Search.cs ├── 84-Largest-Rectangle-in-Histogram.cs ├── 846-Hand-of-Straights.cs ├── 853-Car-Fleet.cs ├── 875-Koko-Eating-Bananas.cs ├── 876-Middle-Of-The-Linked-List.cs ├── 90-Subsets-II.cs ├── 909-Snakes-and-Ladders.cs ├── 91-Decode-Ways.cs ├── 97-Interleaving-String.cs ├── 98-Validate-Binary-Search-Tree.cs ├── 981-Time-Based-Key-Value-Store.cs └── 994-Rotting-Oranges.cs ├── go ├── 1-Two-Sum.go ├── 100-Same-Tree.go ├── 102-Binary-Tree-Level-Order-Traversal.go ├── 104-Maximum-Depth-of-Binary-Tree.go ├── 11-Container-with-Most-Water.go ├── 110-Balanced-Binary-Tree.go ├── 121-Best-Time-To-Buy-And-Sell-Stock.go ├── 124-Binary-Tree-Maximum-Path-Sum.go ├── 125-Valid-Palindrome.go ├── 128-Longest-Consecutive-Sequence.go ├── 13-Roman-To-Integer.go ├── 130-Surrounded-Regions.go ├── 131-Palindrome-Partitioning.go ├── 134-Gas-Station.go ├── 136-Single-Number.go ├── 141-Linked-List-Cycle.go ├── 143-Reorder-List.go ├── 1448-Count-Good-Nodes-in-BT.go ├── 15-3Sum.go ├── 150-Evaluate-Reverse-Polish-Notation.go ├── 152-Maximum-Product-Subarray.go ├── 153-Find-Minimum-in-Rotated-Sorted-Array.go ├── 155-Min-Stack.go ├── 167-Two-Sum-II.go ├── 17-Letter-Combinations-of-a-Phone-Number.go ├── 19-Remove-Nth-Node-From-End-of-List.go ├── 190-Reverse-Bits.go ├── 191-Number-of-1-Bits.go ├── 198-House-Robber.go ├── 20-Valid-Parentheses.go ├── 202-Happy-Number.go ├── 206-Reverse-Linked-List.go ├── 208-Implement-Trie.go ├── 21-Merge-Two-Sorted-Lists.go ├── 213-House-Robber-II.go ├── 217-Contains-Duplicate.go ├── 22-Generate_Parentheses.go ├── 226-Invert-Binary-Tree.go ├── 230-Kth-Smallest-Element-in-a-BST.go ├── 235-Lowest-Common-Ancestor-Of-BST.go ├── 236-Lowest-Common-Ancestor-of-Binary-Tree.go ├── 238-Product-Of-Array-Except-Self.go ├── 239-Sliding-Window-Maximum.go ├── 24-Swap-Nodes-in-Pairs.go ├── 242-Valid-Anagram.go ├── 26-Remove-Duplicates-From-Sorted-Array.go ├── 268-Missing-Number.go ├── 27-Remove-Element.go ├── 287-Find-the-Duplicate-Number.go ├── 3-Longest-Substring-Without-Repeating-Characters.go ├── 309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.go ├── 33-Search-in-Rotated-Sorted-Array.go ├── 338-Counting-Bits.go ├── 347-Top-K-Frequent-Elements.go ├── 36-Valid-Sudoku.go ├── 371-Sum-of-Two-Integers.go ├── 39-Combination-Sum.go ├── 40-Combination-Sum-II.go ├── 42-Trapping-Rain-Water.go ├── 424-Longest-Repeating-Character-Replacement.go ├── 435-Non-Overlapping-Intervals.go ├── 45-Jump-Game-II.go ├── 46-Permutations.go ├── 48-Rotate-Image.go ├── 49-Group-Anagrams.go ├── 494-Target-Sum.go ├── 51-N-Queens.go ├── 53-Maximum-Subarray.go ├── 543-Diameter-of-Binary-Tree.go ├── 55-Jump-Game.go ├── 56-Merge-Intervals.go ├── 567-Permutation-In-String.go ├── 572-Subtree-of-Another-Tree.go ├── 62-Unique-Paths.go ├── 63-Unique-Paths-II.go ├── 66-Plus-One.go ├── 684-Redundant-Connection.go ├── 695-Max-Area-Of-Island.go ├── 7-Reverse-Integer.go ├── 70-Climbing-Stairs.go ├── 704-Binary-Search.go ├── 73-Set-Matrix-Zeroes.go ├── 739-Daily-Temperatures.go ├── 74-Search-A-2D-Matrix.go ├── 746-Min-Cost-Climbing-Stairs.go ├── 75-Sort-Colors.go ├── 76-Minimum-Window-Substring.go ├── 763-Partition-Labels.go ├── 78-Subsets.go ├── 787-Cheapest-Flights-Within-K-Stops.go ├── 79-Word-Search.go ├── 83-Remove-Duplicates-from-Sorted-List.go ├── 852-Peak-Index-In-A-Mountain-Array.go ├── 875-Koko-Eating-Bananas.go ├── 876-Middle-Of-The-Linked-List.go ├── 90-Subsets-II.go └── 98-Validate-Binary-Search-Tree.go ├── java ├── 1-Two-Sum.java ├── 10-Regular-Expression-Matching.java ├── 100-Same-Tree.java ├── 102-Binary-Tree-Level-Order-Traversal.java ├── 104-Maximum-Depth-of-Binary-Tree.java ├── 1046-Last-Stone-Weight.java ├── 105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.java ├── 106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.java ├── 107-Binary-Tree-Level-Order-Traversal-II.java ├── 11-Container-With-Most-Water.java ├── 110-Balanced-Binary-Tree.java ├── 1143-Longest-Common-Subsequence.java ├── 115-Distinct-Subsequences.java ├── 1155-Number-of-Dice-Rolls-With-Target-Sum.java ├── 1160-Find-Words-That-Can-Be-Formed-by-Characters.java ├── 119-Pascal's-Triangle-II.java ├── 121-Best-Time-to-Buy-and-Sell-Stock.java ├── 124-Binary-Tree-Maximum-Path-Sum.java ├── 125-Valid-Palindrome.java ├── 127-Word-Ladder.java ├── 1275-Find-Winner-on-a-Tic-Tac-Toe-Game.java ├── 128-Longest-Consecutive-Sequence.java ├── 130-Surrounded-Regions.java ├── 131-Palindrome-Partitioning.java ├── 133-Clone-Graph.java ├── 134-Gas-Station.java ├── 136-Single-Number.java ├── 138-Copy-List-with-Random-Pointer.java ├── 139-Word- Break.java ├── 141. Linked List Cycle.java ├── 143-Reorder-List.java ├── 1448-Count-Good-Nodes-in-Binary-Tree.java ├── 146-LRU-Cache.java ├── 15-3Sum.java ├── 150-Evaluate-Reverse-Polish-Notation.java ├── 152-Maximum-Product-Subarray.java ├── 153-Find-Minimum-in-Rotated-Sorted-Array.java ├── 155-Min-Stack.java ├── 1584-Min-Cost-to-Connect-All-Points.java ├── 162. Find Peak Element ├── 167-Two-Sum-II.java ├── 17-Letter-Combinations-of-a-Phone-Number.java ├── 1851-Minimum-Interval-to-Include-Each-Query.java ├── 187-Repeated-DNA-Sequences.java ├── 1899-Merge-Triplets-To-Form-Target-Triplet.java ├── 19-Remove-Nth-Node-From-End-of-List.java ├── 19-Remove-Nth-Node.java ├── 190-Reverse-Bits.java ├── 191-Number-of-1-Bits.java ├── 198-House-Robber.java ├── 199-Binary-Tree-Right-Side-View.java ├── 2-Add-Two-Numbers.java ├── 20-Valid-Parentheses.java ├── 200-Number-of-Islands.java ├── 2013-Detect-Squares.java ├── 202-Happy-Number.java ├── 206. Reverse Linked List.java ├── 207-Course-Schedule.java ├── 208-Implement-Trie-Prefix-Tree.java ├── 21-Merge-Two-Sorted-Lists.java ├── 210-Course-Schedule-II.java ├── 211-Design-Add-and-Search-Words-Data-Structure.java ├── 212-Word-Search-II.java ├── 213-House-Robber-II.java ├── 2149. Rearrange Array Elements by Sign ├── 215-Kth-Largest-Element-in-an-Array.java ├── 217-Contains-Duplicate.java ├── 22-Generate-Parentheses.java ├── 226-Invert-Binary-Tree.java ├── 23-Merge-k-Sorted-Lists.java ├── 230-Kth-Smallest-Element-in-a-BST.java ├── 2309.-Greatest-English-Letter-in-Upper-and-Lower-Case.java ├── 231-Power-of-Two ├── 2310-Sum-of-Numbers-With-Units-Digit-K.java ├── 2328-Number-of-Increasing-Paths-in-a-Grid.java ├── 234. Palindrome Linked List.java ├── 235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.java ├── 236-Lowest-Common-Ancestor-of-a-Binary-Tree.java ├── 237-delete-node-in-a-linked-list ├── 237-delete-node-in-a-linked-list.java ├── 238-Product-of-Array-Except-Self.java ├── 239-Sliding-Window-Maximum.java ├── 24 Swap Nodes in Pairs.java ├── 242-Valid-Anagram.java ├── 25-Reverse-Nodes-in-k-Group.java ├── 252-Meeting-Rooms.java ├── 253-Meeting-Rooms-ii.java ├── 261-Graph-Valid-Tree.java ├── 268-Missing-Number.java ├── 269-Alien-Dictionary.java ├── 27-Remove-Element.java ├── 271-Encode-and-Decode-Strings.java ├── 279-Perfect-Squares.java ├── 286-Walls-and-Gates.java ├── 287-Find-the-Duplicate-Number.java ├── 295-Find-Median-from-Data-Stream.java ├── 297-Serialize-and-Deserialize-Binary-Tree.java ├── 3-Longest-Substring-Without-Repeating-Characters.java ├── 300-Longest-Increasing-Subsequence.java ├── 309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.java ├── 312-Burst-Balloons.java ├── 322-Coin-Change.java ├── 323-Number-of-Connected-Components-in-an-Undirected-Graph.java ├── 329-Longest-Increasing-Path-in-a-Matrix.java ├── 33-Search-In-Rotated-Sorted-Array.java ├── 332-Reconstruct-Itinerary.java ├── 338-Counting-Bits.java ├── 342-Power-of-Four.java ├── 347-Top-K-Frequent-Elements.java ├── 355-Design-Twitter.java ├── 36-Valid-Sudoku.java ├── 37-Sudoku-Solver.java ├── 371-Sum-of-Two-Integers.java ├── 39-Combination-Sum.java ├── 4-Median-of-Two-Sorted-Arrays.java ├── 40-Combination-Sum-II.java ├── 416-Partition-Equal-Subset-Sum.java ├── 417-Pacific-Atlantic-Water-Flow.java ├── 42-Trapping-Rain-Water.java ├── 424-Longest-Repeating-Character-Replacement.java ├── 43-Multiply-Strings.java ├── 435-Non-Overlapping-Intervals.java ├── 448-Find-All-Numbers-Disappeared-in-an-Array.java ├── 45-Jump-game-II.java ├── 46-Permutations.java ├── 48-Rotate-Image.java ├── 49-Group-Anagrams.java ├── 494-Target-Sum.java ├── 5-Longest-Palindromic-Substring.java ├── 50-Pow(x, n).java ├── 51-N-Queens.java ├── 518-Coin-Change-2.java ├── 53-Maximum-Subarray.java ├── 54-Spiral-Matrix.java ├── 543-Diameter-of-Binary-Tree.java ├── 55-Jump-Game.java ├── 56-Merge-Intervals.java ├── 560-Subarray-Sum-Equals-K.java ├── 567-Permutation-in-String.java ├── 57-Insert-Interval.java ├── 572-Subtree-of-Another-Tree.java ├── 6-Zigzag-Conversion.java ├── 60-Permutation-Sequence.java ├── 617-Merge-Two-Binary-Trees.java ├── 62-Unique-Paths.java ├── 621-Task-Scheduler.java ├── 63-Unique-Paths-II.java ├── 637-Average-of-Levels-in-Binary-Tree.java ├── 64-Minimum-Path-Sum.java ├── 647-Palindromic-Substrings.java ├── 66-Plus-One.java ├── 662-Maximum-Width-of-Binary-Tree.java ├── 677. Map Sum Pairs ├── 678-Valid-Parenthesis-String.java ├── 684-Redundant-Connection.java ├── 695-Max-Area-of-Island.java ├── 7-Reverse-Integer.java ├── 70-Climbing-Stairs.java ├── 70-climbing-stairs.java ├── 703-Kth-Largest-Element-in-a-Stream.java ├── 704-Binary-Search.java ├── 713-Subarray-Product-Less-Than-K.java ├── 72-Edit-Distance.java ├── 73-Set-Matrix-Zeroes.java ├── 739-Daily-Temperatures.java ├── 74-Search-A-2D-Matrix.java ├── 743-Network-Delay-Time.java ├── 746-Min-Cost-Climbing-Stairs.java ├── 75-Sort-Colors.java ├── 752-Open-the-lock.java ├── 76-Minimum-Window-Substring.java ├── 763-Partition-Labels.java ├── 767-Reorganize-String.java ├── 778-Swim-in-Rising-Water.java ├── 779-K-th-Symbol-in-Grammar.java ├── 78-Subsets.java ├── 787-Cheapest-Flights-Within-K-Stops.java ├── 79-Word-Search.java ├── 797-All-Paths-From-Source-to-Target.java ├── 81-Search-In-Rotated-Sorted-Array-II.java ├── 83. Remove Duplicates from Sorted List.java ├── 84-Largest-Rectangle-in-Histogram.java ├── 846-Hand-of-Straights.java ├── 852. Peak Index in a Mountain Array.java ├── 853-Car Fleet.java ├── 863-All-Nodes-Distance-K-in-Binary-Tree.java ├── 875-Koko-Eating-Bananas.java ├── 876-middle-of-the-linked-list.java ├── 876. Middle of the Linked List.java ├── 90-Subsets-II.java ├── 91-Decode-Ways.java ├── 97-Interleaving-String.java ├── 973-K-Closest-Points-to-Origin.java ├── 98-Validate-Binary-Search-Tree.java ├── 981-Time-Based-Key-Value-Store.java ├── 986-Interval-List-Intersections.java ├── 994-Rotting-Oranges.java ├── Binary-Tree-Level-Order-Traversal.java ├── BinarySearchTreeImpl.java ├── CheckNumberInString.java ├── Dijkstra's Algorithm ├── FindMiddleIndex.java ├── LCM_GCD.java ├── LaunchingExternalApps.java ├── NOTES.md ├── NimGame.java ├── Number_of_Dice_Rolls_With_Target_Sum.java ├── Prim's Algorithm ├── complexMath.java ├── flatten.java ├── inorder.java ├── isPalindrome.java ├── kruskal-algorithm ├── leftview.java ├── maxpathsum.java ├── preorder.java └── swapPairs.java ├── javascript ├── 1-Two-Sum.js ├── 10-Regular-Expression-Matching.js ├── 100-Same-Tree.js ├── 102-Binary-Tree-Level-Order-Traversal.js ├── 104-Maximum-Depth-of-Binary-Tree.js ├── 1046-Last-Stone-Weight.js ├── 105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.js ├── 108-Convert-Sorted-Array-to-Binary-Search-Tree.js ├── 11-Container-With-Most-Water.js ├── 110-Balanced-Binary-Tree.js ├── 1143-Longest-Common-Subsequence.js ├── 115-Distinct-Subsequences.js ├── 1209-Remove-All-Adjacent-Duplicates-in-String-II.js ├── 121-Best-Time-to-Buy-and-Sell-Stock.js ├── 124-Binary-Tree-Maximum-Path-Sum.js ├── 125-Valid-Palindrome.js ├── 127-Word-Ladder.js ├── 128-Longest-consecutive-sequence.js ├── 13-Roman-to-Integer.js ├── 130-Surrounded-Regions.js ├── 131-Palindrome-Partitioning.js ├── 133-Clone-Graph.js ├── 134-Gas-Station.js ├── 136-Single-Number.js ├── 138-Copy-List-with-Random-Pointer.js ├── 139-Word-Break.js ├── 141-Linked-List-Cycle.js ├── 143-Reorder-List.js ├── 1448-Count-Good-Nodes-in-Binary-Tree.js ├── 146-LRU-Cache.js ├── 15-3Sum.js ├── 150-Evaluate-Reverse-Polish-Notation.js ├── 152-Maximum-Product-Subarray.js ├── 153-Find-Minimum-in-Rotated-Sorted-Array.js ├── 155-Min-Stack.js ├── 1584-Min-Cost-to-Connect-all-Points.js ├── 160-Intersection-of-Two-Linked-Lists.js ├── 167-Two-Sum-II.js ├── 17-Letter-Combinations-of-a-Phone-Number.js ├── 173-Binary-Search-Tree-Iterator.js ├── 1899-Merge-Triplets-to-Form-Target-Triplet.js ├── 19-Remove-Nth-Node-From-End-of-List.js ├── 190-Reverse-Bits.js ├── 191-Number-of-1-bits.js ├── 198-House-Robber.js ├── 199-binary-tree-right-side-view.js ├── 2-Add-Two-Numbers.js ├── 20-Valid-Parentheses.js ├── 200-Number-of-Islands.js ├── 2013-Detect-Squares.js ├── 202-Happy-Number.js ├── 206-Reverse-Linked-List.js ├── 207-Course-Schedule.js ├── 207-canFinish.js ├── 208-Implement-Trie.js ├── 21-Merge-Two-Sorted-Lists.js ├── 210-Course-Schedule-II.js ├── 211-Design-Add-and-Search-Words-Data-Structure.js ├── 212-Word-Search-ii.js ├── 213-House-Robber-II.js ├── 217-Contains-Duplicate.js ├── 22-Generate-Parentheses.js ├── 226-Invert-Binary-Tree.js ├── 23-Merge-K-Sorted-Lists.js ├── 230-Kth-Smallest-Element-in-a-BST.js ├── 234-Palindrome-Linked-List.js ├── 235-lowest-common-ancestor-of-a-binary-search-tree.js ├── 238-Product-of-Array-Except-Self.js ├── 239-Sliding-Window-Maximum.js ├── 242-Valid-Anagram.js ├── 25-Reverse-Nodes-in-K-Group.js ├── 252-Meeting-Rooms.js ├── 253-Meeting-Rooms-ii.js ├── 261-Graph-Valid-Tree.js ├── 268-Missing-Number.js ├── 269-Alien-Dictionary.js ├── 271-Encode-and-Decode-Strings.js ├── 286-Walls-And-Gates.js ├── 287-Find-the-Duplicate-Number.js ├── 295-Find-Median-from-Data-Stream.js ├── 297-Serialize-and-Deserialize-Binary-Tree.js ├── 3-Longest-Substring-Without-Repeating-Characters.js ├── 300-Longest-Increasing-Subsequence.js ├── 309-Best-Time-To-Buy-And-Sell-Stock-With-Cooldown.js ├── 312-Burst-Balloons.js ├── 322-Coin-Change.js ├── 323-countComponents.js ├── 329-Longest-Increasing-Path-in-a-Matrix.js ├── 33-Search-in-Rotated-Sorted-Array.js ├── 332-Reconstruct-Itinerary.js ├── 338-Counting-Bits.js ├── 347-Top-K-Frequent-Elements.js ├── 35-Search-Insert-Position.js ├── 355-Design-Twitter.js ├── 36-Valid-Sudoku.js ├── 371-Sum-of-Two-Integers.js ├── 39-Combination-Sum.js ├── 4-Median-Of-Two-Sorted-Arrays.js ├── 40-Combination-Sum-II.js ├── 416-Partition-Equal-Subset-Sum.js ├── 417-Pacific-Atlantic-Water-Flow.js ├── 42-Trapping-Rain-Water.js ├── 424-Longest-Repeating-Character-Replacement.js ├── 43-Multiply-Strings.js ├── 435-Non-overlapping-Intervals.js ├── 45-Jump-Game-II.js ├── 46-Permutations.js ├── 473-Matchsticks-To-Square.js ├── 48-Rotate-Image.js ├── 49-Group-Anagrams.js ├── 49-Rotate-Image.js ├── 494-Target-Sum.js ├── 5-Longest-Palindromic-Substring.js ├── 50. Pow(x, n).js ├── 51-solveNQueens.js ├── 518-Coin-Change-2.js ├── 52-totalNQueens.js ├── 53-Maximum-Subarray.js ├── 54-Spiral-Matrix.js ├── 543-Diameter-Of-Binary-Tree.js ├── 55-Jump-Game.js ├── 56-Merge-Intervals.js ├── 567-Permutation-In-String.js ├── 57-Insert-Interval.js ├── 572-Subtree-of-Another-Tree.js ├── 62-Unique-Paths.js ├── 621-Task-Scheduler.js ├── 647-Palindromic-Substrings.js ├── 66-plus-one.js ├── 678-Valid-Parenthesis-String.js ├── 684-Redundant-Connection.js ├── 695-Max-Area-Of-Island.js ├── 7-Reverse-Integer.js ├── 70-Climbing-Stairs.js ├── 703-Kth-Largest-Element-In-A-Stream.js ├── 704-Binary-Search.js ├── 72-Edit-Distance.js ├── 73-Set-Matrix-Zeroes.js ├── 739-daily-temperatures.js ├── 74-Search-A-2D-Matrix.js ├── 743-Network-Delay-Time.js ├── 746-Min-Cost-Climbing-Stairs.js ├── 76-Minimum-Window-Substring.js ├── 763-Partition-Labels.js ├── 778-Swim-in-Rising-Water.js ├── 78-Subsets.js ├── 787-Cheapest-Flights-Within-K-Stops.js ├── 79-Word-Search.js ├── 84-Largest-Rectangle-in-Histogram.js ├── 846-Hand-of-Straights.js ├── 853-Car-Fleet.js ├── 875-Koko-Eating-Bananas.js ├── 9-Palindrome-Number.js ├── 90-Subsets-II.js ├── 91-Decode-Ways.js ├── 937-K-Closest-Points-To-Origin.js ├── 97-Interleaving-String.js ├── 973-K-Closest-Points-to-Origin.js ├── 98-Validate-Binary-Search-Tree.js ├── 981-Time-Based-Key-Value-Store.js ├── 994-Rotting-Oranges.js └── _215-Kth-Largest-Element-In-An-Array.js ├── jewel_and_stone.py ├── kotlin ├── 1-Two-Sum.kt ├── 100-Same-Tree.kt ├── 102-Binary-Tree-Level-Order-Traversal.kt ├── 104-Maximum-Depth-Of-Binary-Tree.kt ├── 1046-Last-Stone-Weight.kt ├── 105-Construct-Binary-Tree-From-Preorder-And-Inorder-Traversal.kt ├── 11-Container-With-Most-Water.kt ├── 110-Balanced-Binary-Tree.kt ├── 1143-Longest-Common-Subsequence.kt ├── 121-Best-Time-to-Buy-and-Sell-Stocks.kt ├── 124-Binary-Tree-Maximumu-Path-Sum.kt ├── 125-Valid-Palindrome.kt ├── 127-Word-Ladder.kt ├── 128-Longest-Consecutive-Sequence.kt ├── 130-Surrounded-Regions.kt ├── 134-Gas-Station.kt ├── 136-Single-Number.kt ├── 138-Copy-List-With-Random-Pointer.kt ├── 141-Linked-List-Cycle.kt ├── 143-Reorder-List.kt ├── 1448-Count-Good-Nodes-In-Binary-Tree.kt ├── 146-LRU-Cache.kt ├── 15-3Sum.kt ├── 150-Evaluate-Reverse-Polish-Notation.kt ├── 152-Maximum-Product-Subarray.kt ├── 153-Find-Minimum-In-Rotated-Sorted-Array.kt ├── 155-Min-Stack.kt ├── 167-Two-Sum-2.kt ├── 19-Remove-Nth-Node-From-End-of-List.kt ├── 190-Reverse-Bits.kt ├── 191-Number-Of-1-Bits.kt ├── 198-House-Robber.kt ├── 199-Binary-Tree-Right-Side-View.kt ├── 2-Add-Two-Numbers.kt ├── 20-Valid-Parentheses.kt ├── 200-Number-Of-Islands.kt ├── 202-Happy-Number.kt ├── 206-Reverse-Linked-List.kt ├── 207-Course-Schedule.kt ├── 208-Implement-Trie.kt ├── 21-Merge-Two-Sorted-Lists.kt ├── 211-Design-Add-And-Search-Words-Data-Structure.kt ├── 212-Word-Search-II.kt ├── 213-House-Robber-II.kt ├── 215-Kth-Largest-Element-In-Array.kt ├── 217-Contains-Duplicate.kt ├── 22-Generate-Parentheses.kt ├── 226-Invert-Binary-Tree.kt ├── 23-Merge-K-Sorted-Lists.kt ├── 230-Kth-Smallest-Element-In-A-BST.kt ├── 235-Lowest-Common-Ancestor-Of-Binary-Search-Tree.kt ├── 238-Product-Of-Array-Except-Self.kt ├── 239-Sliding-Window-Maximum.kt ├── 242-Valid-Anagram.kt ├── 25-Reverse-Nodes-In-K-Group.kt ├── 268-Missing-Number.kt ├── 287-Find-The-Duplicate-Number.kt ├── 295-Find-Median-From-Data-Stream.kt ├── 297-Serialize-And-Deserialize-Binary-Tree.kt ├── 3-Longest-Substring-Without-Repeating-Characters.kt ├── 309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.kt ├── 322-Coin-Change.kt ├── 329-Longest-Increasing-Path-In-A-Matrix.kt ├── 33-Search-In-Rotated-Sorted-Array.kt ├── 332-Reconstruct-Itinerary.kt ├── 338-Counting-Bits.kt ├── 33_Search_In_Rotated_Sorted_Array.kt ├── 347-Top-K-Frequent-Elements.kt ├── 36-Valid-Sudoku.kt ├── 371-Sum-Of-Two-Integers.kt ├── 39-Combination-Sum.kt ├── 4-Median-Of-Two-Sorted-Arrays.kt ├── 40-Combination-Sum.kt ├── 417-Pacific-Atlantic-Waterflow.kt ├── 42-Trapping-Rain-Water.kt ├── 424-Longest-Repeating-Character-Replacement.kt ├── 45-Jump-Game-II.kt ├── 46-Permutations.kt ├── 49-Group-Anagrams.kt ├── 53-Maximum-Subarray.kt ├── 54-Spiral-Matrix.kt ├── 543-Diameter-of-Binary-Tree.kt ├── 55-Jump-Game.kt ├── 56-Merge-Intervals.kt ├── 567-Permutation-In-String.kt ├── 572-Subtree-Of-Another-Tree.kt ├── 62-Unique-Paths.kt ├── 66-Plus-One.kt ├── 684-Redundant-Connection.kt ├── 695-Max-Area-Of-Island.kt ├── 7-Reverse-Integer.kt ├── 70-Climbing-Stairs.kt ├── 704-Binary-Search.kt ├── 73-Set-Matrix-Zeros.kt ├── 739-Daily-Temperatures.kt ├── 74-Search-A-2D-Matrix.kt ├── 746-Min-Cost-Climbing-Stairs.kt ├── 76-Minimum-Window-Substring.kt ├── 78-Subsets.kt ├── 787-Cheapest-Flights-Within-K-Stops.kt ├── 79-Word-Search.kt ├── 84-Largest-Rectangle-In-Histogram.kt ├── 853-Car-Fleet.kt ├── 875-Koko-Eating-Bananas.kt ├── 90-Subsets-II.kt ├── 91-Decode-Ways.kt ├── 973-K-Closest-Points-To-Origin.kt ├── 98-Validate-Binary-Search-Tree.kt └── 994-Rotting-Oranges.kt ├── logo.png ├── python ├── 005_Longest_Palindromic_Substring.py ├── 013_Roman_to_Integer.py ├── 061_Rotate_List.py ├── 1-Two-Sum.py ├── 10-Regular-Expression-Matching.py ├── 100-Same-Tree.py ├── 102-Binary-Tree-Level-Order-Traversal.py ├── 104-Maximum-Depth-of-Binary-Tree.py ├── 1046-Last-Stone-Weight.py ├── 105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.py ├── 11-Container-With-Most-Water.py ├── 110-Balanced-Binary-Tree.py ├── 1137-N-th-Tribonacci-Number.py ├── 1143-Longest-Common-Subsequence.py ├── 115-Distinct-Subsequences.py ├── 118-Pascal-Triangle.py ├── 118-Pascals-Triangle.py ├── 119-Pascal-Triangle-II.py ├── 12-Integer-To-Roman.py ├── 1209-Remove-All-Adjacent-Duplicates-in-String-II.py ├── 121-Best-Time-To-Buy-and-Sell-Stock.py ├── 1220-Count-Vowels-Permutation.py ├── 1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters.py ├── 124-Binary-Tree-Maximum-Path-Sum.py ├── 125-Valid-Palindrome.py ├── 127-Word-Ladder.py ├── 128-Longest-consecutive-sequence.py ├── 1299-Replace-Elements-With-Greatest-Element-On-Right-Side.py ├── 13-Roman-To-Integer.py ├── 130-Surrounded-Regions.py ├── 131-Palindrome-Partitioning.py ├── 133-Clone-Graph.py ├── 134-Gas-Station.py ├── 136-Single-Number.py ├── 138-Copy-List-With-Random-Pointer.py ├── 1383-Maximum-Performance-Of-A-Team.py ├── 139-Word-Break.py ├── 14-Longest-Common-Prefix.py ├── 141-Linked-List-Cycle.py ├── 143-Reorder-List.py ├── 1448-Count-Good-Nodes-in-Binary-Tree.py ├── 146-LRU-Cache.py ├── 1472-Design-Browser-History.py ├── 15-3Sum.py ├── 150-Evaluate-Reverse-Polish-Notation.py ├── 152-Maximum-Product-Subarray.py ├── 153-Find-Minimum-in-Rotated-Sorted-Array.py ├── 155-Min-Stack.py ├── 1584-Min-Cost-to-Connect-all-Points.py ├── 160-Intersection-of-Two-Linked-Lists.py ├── 1641-Count-Sorted-Vowel-Strings.cpp ├── 167-Two-Sum-II.py ├── 17-Letter-Combinations-of-a-Phone-Number.py ├── 18-4Sum.py ├── 1849-Splitting-A-String-Into-Descending-Consecutive-Values.py ├── 1851-Minimum-Interval-to-Include-Each-Query.py ├── 1899-Merge-Triplets-to-Form-Target-Triplet.py ├── 19-Remove-Nth-node-from-end-of-List.py ├── 190-Reverse-Bits.py ├── 1905-Count-Sub-Islands.py ├── 191-Number-of-1-Bits.py ├── 1920. Build Array from Permutation.py ├── 198-House-Robber.py ├── 1980-Find-Unique-Binary-String.py ├── 1985-Find-The-Kth-Largest-Integer-In-The-Array.py ├── 199-Binary-Tree-Right-Side-View.py ├── 2-Add-Two-Numbers.py ├── 20-Valid-Parentheses.py ├── 200-Number-of-Islands.py ├── 2013-Detect-Squares.py ├── 202-Happy-Number.py ├── 206-Reverse-Linked-List.py ├── 207-Course-Schedule.py ├── 208-Implement-Trie.py ├── 21-Merge-Two-Sorted-Lists.py ├── 210-Course-Schedule-II.py ├── 211-Design-Add-and-Search-Words-Data-Structure.py ├── 212-Word-Search-II.py ├── 213-House-Robber-II.py ├── 215-Kth-Largest-Element-in-an-Array.py ├── 217-Contains-Duplicate.py ├── 22-Generate-Parentheses.py ├── 221-Maximal-Square.py ├── 226-Invert-Binary-Tree.py ├── 23-Merge-K-Sorted-Lists.py ├── 230-Kth-Smallest-Element-in-a-BST.py ├── 235-lowest-common-ancestor-of-a-binary-search-tree.py ├── 236-Lowest-Common-Ancestor-of-a-Binary-Tree.py ├── 238-Product-of-array-except-self.py ├── 239-Sliding-Window-Maximum.py ├── 24-Swap-Nodes-in-Pairs.py ├── 242-Valid-Anagrams.py ├── 25-Reverse-Nodes-in-K-Group.py ├── 252-Meeting-Rooms.py ├── 253-Meeting-Rooms-ii.py ├── 26-Remove-Duplicates-from-Sorted Array.py ├── 261-Graph-Valid-Tree.py ├── 268-Missing-Number.py ├── 269-Alien-Dictionary.py ├── 27-Remove-Element.py ├── 271-Encode-and-Decode-Strings.py ├── 28-Implement-strStr.py ├── 286-Walls-and-Gates.py ├── 287-Find-The-Duplicate-Number.py ├── 290-Word-Pattern.py ├── 295-Find-Median-from-Data-Stream.py ├── 297-Serialize-and-Deserialize-Binary-Tree.py ├── 3-Longest-Substring-Without-Repeating-Characters.py ├── 300-Longest-Increasing-Subsequence.py ├── 309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.py ├── 312-Burst-Balloons.py ├── 322-Coin-Change.py ├── 323-Number-of-Connected-Components-in-an-Undirected-Graph.py ├── 329-Longest-Increasing-Path-in-a-Matrix.py ├── 33-Search-In-Rotated-Sorted-Array.py ├── 332-Reconstruct-Itinerary.py ├── 338-Counting-Bits.py ├── 34-Find-First-and-Last-Position-of-Element-in-Sorted-Array.py ├── 347-Top-k-frequent-elements.py ├── 35-Search-Insert-Position.py ├── 355-Design-Twitter.py ├── 36-Valid-Sudoku.py ├── 367-Valid-Perfect-Square.py ├── 371-Sum-of-Two-Integers.py ├── 377-Combination-Sum-IV.py ├── 39-Combination-Sum.py ├── 392-Is-Subsequence.py ├── 394-decode-string.py ├── 4-median-of-two-sorted-arrays.py ├── 40-Combination-Sum-II.py ├── 40-Combinations-Sum-ii.py ├── 41-First-Missing-Positive.py ├── 410-Split-Array-Largest-Sum.py ├── 416-Partition-Equal-Subset-Sum.py ├── 417-Pacific-Atlantic-Waterflow.py ├── 42-Trapping-Rain-Water.py ├── 424-Longest-Repeating-Character-Replacement.py ├── 43-Multiply-Strings.py ├── 43-Number_of_Connected_Components_in_an_Undirected_Graph.py ├── 435-Non-Overlapping-Intervals.py ├── 438-Find-All-Anagrams-In-A-String.py ├── 441-Arranging-Coin.py ├── 448-Find-all-Numbers-Disappeared-in-an-Array.py ├── 45-Jump-Game-II.py ├── 46-Permutations.py ├── 463-Island-Perimeter.py ├── 473-Matchsticks-to-Square.py ├── 48-Rotate-Image.py ├── 49-Group-Anagrams.py ├── 494-Target-Sum.py ├── 5-Longest-Palindromic-Substring.py ├── 50-Pow(x, n).py ├── 50. Pow(x, n).py ├── 509-Fibonacci-Number.py ├── 51-N-Queens.py ├── 518-coin-change-2.py ├── 53-Maximum-Subarray.py ├── 54-Spiral-Matrix.py ├── 543-Diameter-of-Binary-Tree.py ├── 55-Jump-Game.py ├── 56-Merge-Intervals.py ├── 567-Permutation-in-String.py ├── 57-Insert-Interval.py ├── 572-Subtree-of-Another-Tree.py ├── 58-Length-Of-Last-Word.py ├── 617-Merge-Two-Binary-Trees.py ├── 62-Unique-Paths.py ├── 621-Task-Scheduler.py ├── 63-Unique-Paths-II.py ├── 647-Palindromic-Substrings.py ├── 658-Find-K-Closest-Elements.py ├── 66-Plus-One.py ├── 673-Number-of-Longest-Increasing-Subsequence.py ├── 678-Valid-Parenthesis-String.py ├── 684-Redundant-Connection.py ├── 695-Max-Area-of-Island.py ├── 7-Reverse-Integer.py ├── 70-Climbing-Stairs.py ├── 703-Kth-Largest-Element-in-a-Stream.py ├── 704-Binary-Search.py ├── 72-Edit-Distance.py ├── 724-Find-Pivot-Index.py ├── 73-Set-Matrix-Zeroes.py ├── 739-Daily-Temperatures.py ├── 74-Search-a-2D-Matrix.py ├── 743-Network-Delay-Time.py ├── 746-Min-Cost-Climbing-Stairs.py ├── 752-Open-the-Lock.py ├── 76-Minimum-Window-Substring.py ├── 763-Partition-Labels.py ├── 767-Reorganize-String.py ├── 778-Swim-in-Rising-Water.py ├── 78-Subsets.py ├── 787-Cheapest-Flights-within-K-stops.py ├── 79-Word-Search.py ├── 84-Largest-Rectangle-in-Histogram.py ├── 846-Hand-of-Straights.py ├── 853-Car-Fleet.py ├── 875-Koko-Eating-Bananas.py ├── 90-Subsets-II.py ├── 901-Online-Stock-Span.py ├── 909-Snakes-and-Ladders.py ├── 91-Decode-ways.py ├── 92-Reverse-Linked-List-II.py ├── 931-Minimum-Falling-Path-Sum.py ├── 94-Binary-Tree-Inorder-Traversal.py ├── 97-Interleaving-Strings.py ├── 973-K-Closest-Points-to-Origin.py ├── 977-Squares-Of-A-Sorted-Array.py ├── 98-Validate-Binary-Search-Tree.py ├── 981-Time-Based-Key-Value-Store.py ├── 994-Rotting-Oranges.py ├── Leetcode 3Sum Problem - 15.py ├── Split a String in Balanced Strings ├── leetcode Swap Nodes in Pairs_24.py ├── leetcode Two Sum_1.py ├── leetcode my calendar III_732.py ├── leetcode_question_18.py ├── longest_palindromic_substring.py └── remove-linked-list.py ├── ruby ├── 0053-Maximum-Subarray.rb ├── 1-Two-Sum.rb ├── 100-Same-Tree.rb ├── 104-Maximum-Depth-of-Binary-Tree.rb ├── 1046-Last-Stone-Weight.rb ├── 11-Container-With-Most-Water.rb ├── 110-Balanced-Binary-Tree.rb ├── 121-Best-Time-To-Buy-and-Sell-Stock.rb ├── 125-Valid-Palindrome.rb ├── 128-Longest-consecutive-sequence.rb ├── 136-Single-Number.rb ├── 141-Linked-List-Cycle.rb ├── 15-3Sum.rb ├── 155-Min-Stack.rb ├── 1584-Min-Cost-to-Connect-All-Points.rb ├── 167-Two-Sum-II.rb ├── 17-Letter-Combinations-Of-A-Phone-Number.rb ├── 190-Reverse-Bits.rb ├── 191-Number-of-1-Bits.rb ├── 198-House-Robber.rb ├── 20-Valid-Parentheses.rb ├── 200-Number-of-Islands.rb ├── 206-Reverse-Linked-List.rb ├── 208-Implement-Trie.rb ├── 21-Merge-Two-Sorted-Lists.rb ├── 211-Design-Add-and-Search-Words-Data-Structure.rb ├── 213-House-Robber-II.rb ├── 217-Contains-Duplicate.rb ├── 226-Invert-Binary-Tree.rb ├── 235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.rb ├── 238-Product-of-array-except-self.rb ├── 242-Valid-Anagrams.rb ├── 268-Missing-Number.rb ├── 271-Encode-and-Decode-Strings.rb ├── 3-Longest-Substring-Without-Repeating-Characters.rb ├── 338-Counting-Bits.rb ├── 347-Top-k-frequent-elements.rb ├── 36-Valid-Sudoku.rb ├── 371-Sum-of-Two-Integers.rb ├── 42-Trapping-Rain-Water.rb ├── 424-Longest-Repeating-Character-Replacement.rb ├── 49-Group-Anagrams.rb ├── 543-Diameter-of-Binary-Tree.rb ├── 572-Subtree-of-Another-Tree.rb ├── 7-Reverse-Integer.rb ├── 70-Climbing-Stairs.rb ├── 703-Kth-Largest-Element-in-a-Stream.rb ├── 704-Binary-Search.rb ├── 746-Min-Cost-Climbing-Stairs.rb └── 78-Subsets.rb ├── rust ├── 1-Two-Sum.rs ├── 11-Container-With-Most-Water.rs ├── 121-Best-Time-To-Buy.rs ├── 125-Valid-Palindrome.rs ├── 128-Longest-Consecutive-Sequence.rs ├── 15-3sum.rs ├── 167-Two-Sum-II.rs ├── 198-House-Robber.rs ├── 208-Implement-Trie.rs ├── 211-Design-Add-And-Search-Words-Data-Structure.rs ├── 212-Word-Search-II.rs ├── 217-Contains-Duplicates.rs ├── 238-Product-Of-Array-Except-Self.rs ├── 242-Valid-Anagram.rs ├── 271-Encode-And-Decode-Strings.rs ├── 347-Top-K-Frequent-Elements.rs ├── 36-Valid-Sudoku.rs ├── 49-Group-Anagrams.rs ├── 70-Climbing-Stairs.rs └── 746-Min-Cost-Climbing-Stairs.rs ├── scala ├── 1-Two-Sum.scala ├── 141-Linked-List-Cycle.scala ├── 153-Find-Minimum-In-Rotated-Sorted-Array.scala ├── 198-House-Robber.scala ├── 2-Add-Two-Numbers.scala ├── 206-Reverse-Linked-List.scala ├── 21-Merge-Two-Sorted-Lists.scala ├── 213-House-Robber-II.scala ├── 217-Contains-Duplicate.scala ├── 3-Longest-Substring-Without-Repeating-Characters.scala ├── 33-Search-in-Rotated-Sorted-Array.scala ├── 435-Non-Overlapping-Intervals.scala ├── 56-Merge-Intervals.scala ├── 572-Subtree-of-Another-Tree.scala ├── 7-Reverse-Integer.scala └── 91-Decode-Ways.scala ├── swift ├── 1-Two-Sum.swift ├── 100-Same-Tree.swift ├── 102-Binary-Tree-Level-Order-Traversal.swift ├── 104-Maximum-Depth-of-Binary-Tree.swift ├── 11-Container-With-Most-Water.swift ├── 110-Balanced-Binary-Tree.swift ├── 1143-Longest-Common-Subsequence.swift ├── 121-Best-Time-to-Buy-and-Sell-Stock.swift ├── 124-Binary-Tree-Maximum-Path-Sum.swift ├── 125-Valid-Palindrome.swift ├── 128-Longest-Consecutive-Sequence.swift ├── 130-Surrounded-Regions.swift ├── 133-Clone-Graph.swift ├── 134-Gas-Station.swift ├── 136-Single-Number.swift ├── 138-Copy-List-with-Random-Pointer.swift ├── 141-Linked-List-Cycle.swift ├── 1448-Count-Good-Nodes-in-Binary-Tree.swift ├── 15-3Sum.swift ├── 150-Evaluate-Reverse-Polish-Notation.swift ├── 152-Maximum-Product-Subarray.swift ├── 153-Find-Minimum-in-Rotated-Sorted-Array.swift ├── 1584-Min-Cost-to-Connect-All-Points.swift ├── 167-Two-Sum-II-Input-Array-Is-Sorted.swift ├── 1899-Merge-Triplets-To-Form-Target-Triplet.swift ├── 19-Remove-Nth-Node-From-End-of-List.swift ├── 190-Reverse-Bits.swift ├── 191-Number-of-1-Bits.swift ├── 198-House-Robber.swift ├── 199-Binary-Tree-Right-Side-View.swift ├── 2-Add-Two-Numbers.swift ├── 20-Valid-Parentheses ├── 200-Number-of-Islands.swift ├── 202-Happy-Number.swift ├── 206-Reverse-Linked-List.swift ├── 207-Course-Schedule.swift ├── 208-Implement-Trie-(Prefix-Tree).swift ├── 21-Merge-Two-Sorted-Lists.swift ├── 213-House-Robber-II.swift ├── 217-Contains-Duplicate.swift ├── 226-Invert-Binary-Tree ├── 230-Kth-Smallest-Element-In-A-BST.swift ├── 235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.swift ├── 238-Product-of-array-except-self.swift ├── 242-Valid-Anagram.swift ├── 261-Graph-Valid-Tree.swift ├── 268-Missing-Number.swift ├── 271-Encode-and-Decode-Strings.swift ├── 287-Find-The-Duplicate-Number.swift ├── 3-Longest-Substring-Without-Repeating-Characters.swift ├── 309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.swift ├── 323-Number-of-Connected-Components-in-an-Undirected-Graph.swift ├── 33-Search-in-Rotated-Sorted-Array.swift ├── 338-Counting-Bits.swift ├── 347-Top-k-frequent-elements.swift ├── 35-Valid-Sudoku.swift ├── 371-Sum-Of-Two-Integers.swift ├── 42-Trapping-Rain-Water.swift ├── 43-Multiply-Strings.swift ├── 45-Jump-Game-II.swift ├── 46-Permutations.swift ├── 48-Rotate-Image.swift ├── 49-Group-Anagrams.swift ├── 50-Pow(x, n).swift ├── 53-Maximum-Subarray.swift ├── 543-Diameter-of-Binary-Tree.swift ├── 55-Jump-Game.swift ├── 57-Insert-Interval.swift ├── 572-Subtree-of-Another-Tree.swift ├── 66-Plus-One.swift ├── 7-Reverse-Integer.swift ├── 70-Climbing-Stairs.swift ├── 703-Kth-Largest-Element-In-A-Stream.swift ├── 704-Binary-Search ├── 72-Edit-Distance.swift ├── 739-Daily-Temperatures.swift ├── 74-Search-A-2D-Matrix.swift ├── 746-Min-Cost-Climbing-Stairs.swift ├── 78-Subsets.swift ├── 79-Word-Search.swift ├── 875-Koko-Eating-Bananas.swift └── 98-Validate-Binary-Search-Tree.swift ├── typescript ├── 1-Two-Sum.ts ├── 10-Regular-Expression-Matching.ts ├── 100-Same-Tree.ts ├── 102-Binary-Tree-Level-Order-Traversal.ts ├── 104-Maximum-Depth-of-Binary-Tree.ts ├── 1046-Last-Stone-Weight.ts ├── 105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.ts ├── 11-Container-With-Most-Water.ts ├── 110-Balanced-Binary-Tree.ts ├── 1143-Longest-Common-Subsequence.ts ├── 115-Distinct-Subsequences.ts ├── 121-Best-Time-To-Buy-and-Sell-Stock.ts ├── 124-Binary-Tree-Maximum-Path-Sum.ts ├── 125-Valid-Palindrome.ts ├── 127-Word-Ladder.ts ├── 128-Longest-Consecutive-Sequence.ts ├── 1299-Replace-Elements-With-Greatest-Element-On-Right-Side.ts ├── 130-Surrounded-Regions.ts ├── 131-Palindrome-Partitioning.ts ├── 133-Clone-Graph.ts ├── 134-Gas-Station.ts ├── 136-Single-Number.ts ├── 138-Copy-List-with-Random-Pointer.ts ├── 139-Word-Break.ts ├── 141-Linked-List-Cycle.ts ├── 143-Reorder-List.ts ├── 1448-Count-Good-Nodes-in-Binary-Tree.ts ├── 15-3Sum.ts ├── 150-Evaluate-Reverse-Polish-Notation.ts ├── 152-Maximum-Product-Subarray.ts ├── 153-Find-Minimum-in-Rotated-Sorted-Array.ts ├── 155-Min-Stack.ts ├── 167-Two-Sum-II.ts ├── 17-Letter-Combinations-of-a-Phone-Number.ts ├── 1899-Merge-Triplets-to-Form-Target-Triplet.ts ├── 19-Remove-Nth-Node-From-End-of-List.ts ├── 190-Reverse-Bits.ts ├── 191-Number-of-1-Bits.ts ├── 198-House-Robber.ts ├── 199-Binary-Tree-Right-Side-View.ts ├── 2-Add-Two-Numbers.ts ├── 20-Valid-Parentheses.ts ├── 200-Number-of-Islands.ts ├── 202-Happy-Number.ts ├── 206-Reverse-Linked-List.ts ├── 207-Course-Schedule.ts ├── 208-Implement-Trie.ts ├── 21-Merge-Two-Sorted-Lists.ts ├── 210-Course-Schedule-II.ts ├── 211-Design-Add-and-Search-Words-Data-Structure.ts ├── 213-House-Robber-II.ts ├── 215-Kth-Largest-Element-in-an-Array.ts ├── 217-Contains-Duplicate.ts ├── 22-Generate-Parentheses.ts ├── 226-Invert-Binary-Tree.ts ├── 23-Merge-k-Sorted-Lists.ts ├── 230-Kth-Smallest-Element-In-A-BST.ts ├── 235-Lowest-Common-Ancestor-of-a-Binary Search-Tree.ts ├── 238-Product-of-Array-Except-Self.ts ├── 242-Valid-Anagram.ts ├── 242-Valid-Anagrams.ts ├── 25-Reverse-Nodes-in-k-Group.ts ├── 261-Graph-Valid-Tree.ts ├── 268-Missing-Number.ts ├── 287-Find-the-Duplicate-Number.ts ├── 3-Longest-Substring-Without-Repeating-Characters.ts ├── 300-Longest-Increasing-Subsequence.ts ├── 309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.ts ├── 312-Burst-Balloons.ts ├── 322-Coin-Change.ts ├── 33-Search-in-Rotated-Sorted-Array.ts ├── 338-Counting-Bits.ts ├── 347-Top-K-Frequent-Elements.ts ├── 36-Valid-Sudoku.ts ├── 371-Sum-Of-Two-Integers.ts ├── 39-Combination-Sum.ts ├── 4-Median-of-Two-Sorted-Arrays.ts ├── 40-Combination-Sum-II.ts ├── 42-Trapping-Rain-Water.ts ├── 424-Longest-Repeating-Character-Replacement.ts ├── 43-Multiply-Strings.ts ├── 435-Non-overlapping-Intervals.ts ├── 45-Jump-Game-II.ts ├── 46-Permutations.ts ├── 48-Rotate-Image.ts ├── 49-Group-Anagrams.ts ├── 494-Target-Sum.ts ├── 5-Longest-Palindromic-Substring.ts ├── 50-Pow.ts ├── 51-N-Queens ├── 518-Coin-Change-II.ts ├── 53-Maximum-Subarray.ts ├── 54-Spiral-Matrix.ts ├── 543-Diameter-of-Binary-Tree.ts ├── 55-Jump-Game.ts ├── 56-Merge-Intervals.ts ├── 567-Permutation-in-String.ts ├── 57-Insert-Interval.ts ├── 572-Subtree-of-Another-Tree.ts ├── 62-Unique-Paths.ts ├── 621-Task-Scheduler.ts ├── 647-Palindromic-Substrings.ts ├── 66-Plus-One.ts ├── 678-Valid-Parenthesis-String.ts ├── 684-Redundant-Connection.ts ├── 695-Max-Area-of-Island.ts ├── 7-Reverse-Integer.ts ├── 70-Climbing-Stairs.ts ├── 704-Binary-Search.ts ├── 73-Set-Matrix-Zeroes.ts ├── 739-Daily-Temperatures.ts ├── 74-Search-a-2D-Matrix.ts ├── 746-Min-Cost-Climbing-Stairs.ts ├── 76-Minimum-Window-Substring.ts ├── 78-Subsets.ts ├── 787-Cheapest-Flights-Within-K-Stops.ts ├── 84-Largest-Rectangle-in-Histogram.ts ├── 846-Hand-of-Straights.ts ├── 853-Car-Fleet.ts ├── 875-Koko-Eating-Bananas.ts ├── 9-Palindrome-Number.ts ├── 90-Subsets-II.ts ├── 91-Decode-Ways.ts ├── 97-Interleaving-String.ts ├── 98-Validate-Binary-Search-Tree.ts ├── 981-Time-Based-Key-Value-Store.ts └── 994-Rotting-Oranges.ts └── weirdTarminal.cpp /array-rever: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int num, *arr, i; 7 | scanf("%d", &num); 8 | arr = (int*) malloc(num * sizeof(int)); 9 | for(i = 0; i < num; i++) { 10 | scanf("%d", arr + i); 11 | } 12 | 13 | int temp; 14 | for(i=0;i val != q -> val)) { 17 | return false; 18 | } 19 | return (isSameTree(p -> left, q -> left) && isSameTree(p -> right, q -> right)); 20 | } -------------------------------------------------------------------------------- /c/104-Maximum-Depth-Of-Binary-Tree.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * struct TreeNode *left; 6 | * struct TreeNode *right; 7 | * }; 8 | */ 9 | 10 | int max(int a, int b) { 11 | if (a > b) { 12 | return a; 13 | } 14 | return b; 15 | } 16 | 17 | 18 | int maxDepth(struct TreeNode* root) { 19 | 20 | if (root == NULL) { 21 | return 0; 22 | } 23 | return max( 24 | maxDepth(root -> left), 25 | maxDepth(root -> right) 26 | ) + 1; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /c/136-Single-Number.c: -------------------------------------------------------------------------------- 1 | int singleNumber(int* nums, int numsSize){ 2 | int res = 0; 3 | for (int i = 0; i < numsSize; i++) { 4 | res = nums[i] ^ res; 5 | } 6 | return res; 7 | } -------------------------------------------------------------------------------- /c/153-Find-Minimum-in-Rotated-Sorted-Array.c: -------------------------------------------------------------------------------- 1 | int findMin(int* nums, int numsSize){ 2 | // set the starting indicies to find minimum pivot 3 | int left = 0; 4 | int right = numsSize - 1; 5 | 6 | while (left < right) { 7 | // calculate middle index 8 | int middle = (left + right) / 2; 9 | 10 | // set the left or right index accordingly 11 | if (nums[middle] > nums[right]) { 12 | left = middle + 1; 13 | } 14 | else { 15 | right = middle; 16 | } 17 | } 18 | return nums[left]; 19 | } -------------------------------------------------------------------------------- /c/190-Reverse-Bits.c: -------------------------------------------------------------------------------- 1 | uint32_t reverseBits(uint32_t n) { 2 | uint32_t res = 0; 3 | 4 | for (int i = 0; i < 32; i++) { 5 | res <<= 1; 6 | res |= n & 1; 7 | n >>= 1; 8 | } 9 | return res; 10 | } -------------------------------------------------------------------------------- /c/191-Number-of-1-Bits.c: -------------------------------------------------------------------------------- 1 | int hammingWeight(uint32_t n) { 2 | int res = 0; 3 | int bit = 0; 4 | while (n != 0) { 5 | bit = n & 1; 6 | if (bit == 1) { 7 | res++; 8 | } 9 | n = n >> 1; 10 | } 11 | return res; 12 | } -------------------------------------------------------------------------------- /c/202-Happy-Number.c: -------------------------------------------------------------------------------- 1 | bool isHappy(int n) { 2 | int slow = n; 3 | int fast = sumSquareDigits(n); 4 | 5 | while (slow != fast) { 6 | fast = sumSquareDigits(sumSquareDigits(fast)); 7 | slow = sumSquareDigits(slow); 8 | } 9 | return fast == 1; 10 | } 11 | 12 | int sumSquareDigits(n) { 13 | int result = 0; 14 | while (n != 0) { 15 | int digit = n % 10; 16 | result += digit * digit; 17 | n /= 10; 18 | } 19 | return result; 20 | } -------------------------------------------------------------------------------- /c/206-Reverse-Linked-List.c: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Definition for singly-linked list. 4 | * struct ListNode { 5 | * int val; 6 | * struct ListNode *next; 7 | * }; 8 | */ 9 | 10 | 11 | struct ListNode* reverseList(struct ListNode* head){ 12 | 13 | if (head == NULL) { 14 | return NULL; 15 | } else if (head -> next == NULL) { 16 | return head; 17 | } 18 | 19 | struct ListNode* lastNode = reverseList(head -> next); 20 | head -> next -> next = head; 21 | head -> next = NULL; 22 | return lastNode; 23 | 24 | } -------------------------------------------------------------------------------- /c/226-Invert-Binary-Tree.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * struct TreeNode *left; 6 | * struct TreeNode *right; 7 | * }; 8 | */ 9 | 10 | struct TreeNode *invertTree(struct TreeNode* root) { 11 | 12 | if (root == NULL) { 13 | return root; 14 | } 15 | struct TreeNode* inverted_right = invertTree(root -> right); 16 | struct TreeNode* inverted_left = invertTree(root -> left); 17 | root -> right = inverted_left; 18 | root -> left = inverted_right; 19 | return root; 20 | } 21 | -------------------------------------------------------------------------------- /c/242-Valid-Anagram.c: -------------------------------------------------------------------------------- 1 | bool isAnagram(char* s, char* t) { 2 | int hash[26] = {0}; 3 | int i = 0; 4 | 5 | while (s[i]) hash[s[i++] - 'a']++; 6 | i = 0; 7 | while (t[i]) hash[t[i++] - 'a']--; 8 | 9 | for (i = 0; i < 26; i++) 10 | if (hash[i] != 0) return false; 11 | return true; 12 | } -------------------------------------------------------------------------------- /c/268-Missing-Number.c: -------------------------------------------------------------------------------- 1 | int missingNumber(int* nums, int numsSize){ 2 | int res = numsSize; 3 | 4 | for (int i = 0; i < numsSize; i++) { 5 | res += i - nums[i]; 6 | } 7 | return res; 8 | } -------------------------------------------------------------------------------- /c/287-Find-The-Duplicate-Number.c: -------------------------------------------------------------------------------- 1 | int findDuplicate(int* nums, int numsSize){ 2 | int slow = nums[0]; 3 | int fast = nums[nums[0]]; 4 | 5 | while (slow != fast) { 6 | slow = nums[slow]; 7 | fast = nums[nums[fast]]; 8 | } 9 | 10 | slow = 0; 11 | while (slow != fast) { 12 | slow = nums[slow]; 13 | fast = nums[fast]; 14 | } 15 | return slow; 16 | } -------------------------------------------------------------------------------- /c/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.c: -------------------------------------------------------------------------------- 1 | int maxProfit(int* prices, int pricesSize){ 2 | int sold = 0; 3 | int hold = INT_MIN; 4 | int rest = 0; 5 | 6 | for (int i = 0; i < pricesSize; i++) { 7 | int prevSold = sold; 8 | sold = hold + prices[i]; 9 | hold = max(hold, rest - prices[i]); 10 | rest = max(rest, prevSold); 11 | } 12 | return max(sold, rest); 13 | } 14 | 15 | // C doesn't have a built-in max function 16 | int max(int a, int b) { 17 | return (a > b) ? a : b; 18 | } -------------------------------------------------------------------------------- /c/371-Sum-of-Two-Integers.c: -------------------------------------------------------------------------------- 1 | int getSum(int a, int b){ 2 | while (b != 0) { 3 | int temp = a ^ b; 4 | b = (unsigned)(a & b) << 1; 5 | a = temp; 6 | } 7 | return a; 8 | } -------------------------------------------------------------------------------- /c/45-Jump-Game-II.c: -------------------------------------------------------------------------------- 1 | int jump(int* nums, int numsSize){ 2 | int left = 0; 3 | int right = 0; 4 | int res = 0; 5 | 6 | while (right < numsSize - 1) { 7 | int maxJump = 0; 8 | for (int i = left; i <= right; i++) { 9 | maxJump = max(maxJump, i + nums[i]); 10 | } 11 | left = right + 1; 12 | right = maxJump; 13 | res += 1; 14 | } 15 | return res; 16 | } 17 | 18 | // C doesn't have a built-in max function 19 | int max(int a, int b) { 20 | return (a > b) ? a : b; 21 | } -------------------------------------------------------------------------------- /c/50-Pow-X-N.c: -------------------------------------------------------------------------------- 1 | double calc(double x, int n) { 2 | long exponent = abs(n); 3 | 4 | if (x == 0.0) 5 | return 0.0; 6 | if (n == 0) 7 | return 1.0; 8 | 9 | double res = calc(x, n/2); 10 | res = res * res; 11 | 12 | if (n%2 == 0) 13 | return res; 14 | else 15 | return x * res; 16 | } 17 | 18 | double myPow(double x, int n){ 19 | double res = calc(x, n); 20 | 21 | if (n >= 0) 22 | return res; 23 | else 24 | return 1.0 / res; 25 | } -------------------------------------------------------------------------------- /c/53-Maximum-Subarray.c: -------------------------------------------------------------------------------- 1 | int maxSubArray(int* nums, int numsSize){ 2 | int result = nums[0]; 3 | int total = 0; 4 | 5 | for (int i = 0; i < numsSize; i++) { 6 | total += nums[i]; 7 | result = max(result, total); 8 | if (total < 0) { 9 | total = 0; 10 | } 11 | } 12 | return result; 13 | } 14 | 15 | // C doesn't have a built-in max function 16 | int max(int a, int b) { 17 | return (a > b) ? a : b; 18 | } -------------------------------------------------------------------------------- /c/55-Jump-Game.c: -------------------------------------------------------------------------------- 1 | bool canJump(int* nums, int numsSize){ 2 | int goal = numsSize - 1; 3 | 4 | for (int i = numsSize - 2; i >= 0; i--) { 5 | if (i + nums[i] >= goal) { 6 | goal = i; 7 | } 8 | } 9 | return goal == 0; 10 | } -------------------------------------------------------------------------------- /c/7-Reverse-Integer.c: -------------------------------------------------------------------------------- 1 | int reverse(int x) { 2 | long reversed_num = 0; 3 | while (x != 0) { 4 | reversed_num = reversed_num * 10 + x % 10; 5 | x /= 10; 6 | } 7 | 8 | if (reversed_num < INT_MIN || reversed_num > INT_MAX) 9 | return 0; 10 | 11 | return reversed_num; 12 | } -------------------------------------------------------------------------------- /c/70-Climbing-Stairs.c: -------------------------------------------------------------------------------- 1 | int climbStairs(int n){ 2 | if (n <= 3) { 3 | return n; 4 | } 5 | 6 | int n1 = 2; 7 | int n2 = 3; 8 | 9 | for (int i = 4; i <= n; i++) { 10 | int temp = n1 + n2; 11 | n1 = n2; 12 | n2 = temp; 13 | } 14 | return n2; 15 | } -------------------------------------------------------------------------------- /c/746-Min-Cost-Climbing-Stairs.c: -------------------------------------------------------------------------------- 1 | int min(int a, int b) { return a > b ? b : a; } 2 | 3 | int minCostClimbingStairs(int *cost, int costSize) { 4 | 5 | for (int i = 2; i < costSize; i++) 6 | cost[i] += min(cost[i - 1], cost[i - 2]); 7 | 8 | return min(cost[costSize - 1], cost[costSize - 2]); 9 | } -------------------------------------------------------------------------------- /cpp/118_pascal_triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> generate(int numRows) { 4 | vector>ans; 5 | ans.push_back({1}); 6 | for(int i=0;ids; 8 | for(int j=0;j<=i+1;++j){ 9 | if(j==0 || j==i+1) 10 | ds.push_back(1); 11 | else 12 | ds.push_back(ans[i][j]+ans[i][j-1]); 13 | } 14 | ans.push_back(ds); 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /cpp/1213-Maximum-Product-Difference-Between-Two-Pairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int maxProductDifference(vector& nums){ 4 | sort(nums.begin(), nums.end()); 5 | return nums.rbegin()[1] * nums.back() - nums[0] * nums[1]; 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /cpp/1299-Replace-Elements-with-Greatest-Element-on-Right-Side.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector replaceElements(vector& arr) { 4 | // O(N) Time Complexity , O(1) Space complexity 5 | int n = arr.size(); 6 | int maxSoFar = arr[n-1]; 7 | arr[n-1] = -1; 8 | 9 | for(int i=n-2;i>=0;i--) 10 | { 11 | int temp = maxSoFar; 12 | if(maxSoFar < arr[i]) maxSoFar = arr[i]; 13 | arr[i] = temp; 14 | } 15 | return arr; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /cpp/136-Single-Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given int array, every element appears twice except 1, find it 3 | Ex. nums = [2,2,1] -> 1, nums = [4,1,2,1,2] -> 4 4 | 5 | a XOR a returns 0, so returns 0 for all except the unique one 6 | 7 | Time: O(n) 8 | Space: O(1) 9 | */ 10 | 11 | class Solution { 12 | public: 13 | int singleNumber(vector& nums) { 14 | int result = 0; 15 | 16 | for (int i = 0; i < nums.size(); i++) { 17 | result = result ^ nums[i]; 18 | } 19 | 20 | return result; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /cpp/152-Maximum-Product-Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProduct(vector& nums) { 4 | int res = nums[0]; 5 | int curMin = 1, curMax = 1; 6 | 7 | for(int i = 0; i < nums.size(); i++) 8 | { 9 | int n = nums[i]; 10 | 11 | int tmp = curMax * n; 12 | curMax = max(max(n * curMax, n * curMin), n); 13 | curMin = min(min(tmp, n * curMin), n); 14 | res = max(res, curMax); 15 | } 16 | 17 | return res; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /cpp/190-Reverse-Bits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse bits of a given integer 3 | Ex. n = 10011100 -> 00111001 = 57 4 | 5 | Shift into result & shift out of n 6 | 7 | Time: O(1) 8 | Space: O(1) 9 | */ 10 | 11 | class Solution { 12 | public: 13 | uint32_t reverseBits(uint32_t n) { 14 | uint32_t result = 0; 15 | 16 | for (int i = 0; i < 32; i++) { 17 | result <<= 1; 18 | result |= n & 1; 19 | n >>= 1; 20 | } 21 | 22 | return result; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /cpp/191-Number-Of-1-Bits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Return number of '1' bits in an int 3 | Ex. n = 00001011 -> 3 4 | 5 | Simply count bit-by-bit & shift it off 6 | 7 | Time: O(1) 8 | Space: O(1) 9 | */ 10 | 11 | class Solution { 12 | public: 13 | int hammingWeight(uint32_t n) { 14 | int bit = 0; 15 | int result = 0; 16 | 17 | while (n != 0) { 18 | bit = n & 1; 19 | if (bit == 1) { 20 | result++; 21 | } 22 | n = n >> 1; 23 | } 24 | 25 | return result; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /cpp/1920-Build-Array-From-Permutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector buildArray(vector& nums){ 4 | vector ans; 5 | for(int & n : nums){ 6 | ans.push_back(nums[n]); 7 | } 8 | return ans; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /cpp/1929-Cocatenation-Of-Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | vector getConcatenation(vector& nums){ 4 | vector ans; 5 | int len; 6 | len = nums.size(); 7 | for(int i = 0; i < 2 * len; i++){ 8 | ans.push_back(nums[i % len]); 9 | } 10 | return ans; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /cpp/2149. rearrange array elements by sign.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector rearrangeArray(vector& nums) { 4 | int x= nums.size(); 5 | vector a(x); 6 | int i=0,j=1; 7 | for(int k=0;k0){ 9 | a[i]=nums[k]; 10 | i+=2; 11 | } 12 | else{ 13 | a[j]=nums[k]; 14 | j+=2; 15 | } 16 | } 17 | return a; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /cpp/2235-Add-Two-Integers.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int sum(int num1, int num2){ 4 | return num1 + num2; 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /cpp/236-Power-Of-Three.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | bool isPowerOfThree(int n){ 4 | if(n <= 0){ 5 | return false; 6 | } 7 | while(n > 1){ 8 | if(n % 3 != 0){ 9 | return false; 10 | } 11 | n = n / 3; 12 | } 13 | return true; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /cpp/326-Power_of_Three: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfThree(int n) { 4 | if(n<1){ 5 | return false; 6 | } 7 | while(n!=1){ 8 | if(n%3!=0){ 9 | return false; 10 | } 11 | n= n/3; 12 | } 13 | return true; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /cpp/342-Power-Of-Four.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | bool isPowerOfFour(int n){ 4 | if(n <= 0){ 5 | return false; 6 | } 7 | bool pow = true; 8 | while((n > 1) && (pow == true)){ 9 | n % 4 == 0 ? n = n / 4 : pow = false; 10 | } 11 | return pow; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /cpp/371-Sum-Of-Two-Integers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given 2 ints, return sum w/o using +/- 3 | Ex. a = 1 b = 2 -> 3, a = 2 b = 3 -> 5 4 | 5 | XOR for addition, AND for carry bit 6 | 7 | Time: O(n) 8 | Space: O(1) 9 | */ 10 | 11 | class Solution { 12 | public: 13 | int getSum(int a, int b) { 14 | while (b != 0) { 15 | int carry = a & b; 16 | a = a ^ b; 17 | b = (unsigned)carry << 1; 18 | } 19 | return a; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /cpp/392-Is-Subsequence.cpp: -------------------------------------------------------------------------------- 1 | // Time Complexity is O(N) where n is the size of the target string. 2 | // Space Complexity is O(1) 3 | 4 | class Solution { 5 | public: 6 | bool isSubsequence(string s, string t) { 7 | int i = 0 , j = 0; 8 | while(j < s.size() && i < t.size()) 9 | { 10 | if(s[j] == t[i]) 11 | j++; 12 | 13 | i++; 14 | } 15 | 16 | if(j >= s.size()) return true; 17 | return false; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /cpp/48-Rotate-Image.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a 2D image matrix, rotate image 90 deg CW 3 | 4 | Transpose + reflect (rev on diag then rev left to right) 5 | 6 | Time: O(n^2) 7 | Space: O(1) 8 | */ 9 | 10 | class Solution { 11 | public: 12 | void rotate(vector>& matrix) { 13 | int n = matrix.size(); 14 | for (int i = 0; i < n; i++) { 15 | for (int j = i; j < n; j++) { 16 | swap(matrix[i][j], matrix[j][i]); 17 | } 18 | reverse(matrix[i].begin(), matrix[i].end()); 19 | } 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /cpp/7. Reverse Integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reverse(int x) { 4 | int ans=0; 5 | while(x!=0){ 6 | int digit=x%10; 7 | if((ans>INT_MAX/10)||(ans& indices) { 4 | char a[s.size()+1]; 5 | a[s.size()]='\0'; 6 | for(int i=0;i 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | cin >> n; 8 | int arr[n]; 9 | for (int i = 0; i < n; i++) 10 | { 11 | arr[i]; 12 | } 13 | 14 | int ans = INT_MIN; 15 | 16 | for (int i = 0; i < n; i++) 17 | { 18 | ans = max(ans, arr[i]); 19 | } 20 | 21 | cout << ans << endl; 22 | } -------------------------------------------------------------------------------- /csharp/1-Two-Sum.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] TwoSum(int[] nums, int target) { 3 | Dictionary indices = new Dictionary(); 4 | 5 | for (int i = 0; i < nums.Length; i++) { 6 | var diff = target - nums[i]; 7 | if (indices.ContainsKey(diff)) { 8 | return new int[] {indices[diff], i}; 9 | } 10 | indices[nums[i]] = i; 11 | } 12 | return null; 13 | } 14 | } 15 | 16 | -------------------------------------------------------------------------------- /csharp/11-Container-With-Most-Water.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int MaxArea(int[] height) { 3 | int res = 0, area = 0, left = 0, right = height.Length-1; 4 | 5 | while (left < right){ 6 | 7 | area = (Math.Min(height[left], height[right])) * (right - left); 8 | res = Math.Max(area, res); 9 | 10 | if(height[left] < height[right]){ 11 | left++; 12 | }else{ 13 | right--; 14 | } 15 | 16 | } 17 | return res; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /csharp/121-Best-Time-To-Buy-and-Sell-Stock.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int MaxProfit(int[] prices) { 3 | int maxProfit = 0; 4 | int minPrice = prices[0]; 5 | 6 | for (int i = 1; i < prices.Length; i++) { 7 | int currPrice = prices[i]; 8 | minPrice = Math.Min(minPrice, currPrice); 9 | maxProfit = Math.Max(maxProfit, currPrice - minPrice); 10 | } 11 | return maxProfit; 12 | } 13 | } -------------------------------------------------------------------------------- /csharp/134-Gas-Station.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int CanCompleteCircuit(int[] gas, int[] cost) { 3 | if (gas.Sum() < cost.Sum()) { 4 | return -1; 5 | } 6 | 7 | int res = 0, total = 0; 8 | 9 | for (int i = 0; i < gas.Length; i++) { 10 | total += gas[i] - cost[i]; 11 | if (total < 0) { 12 | total = 0; 13 | res = i + 1; 14 | } 15 | } 16 | return res; 17 | } 18 | } -------------------------------------------------------------------------------- /csharp/136-Single-Number.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int SingleNumber(int[] nums) { 3 | var x = 0; 4 | for (int i=0;i < nums.Length; i++) 5 | { 6 | x ^= nums[i]; 7 | } 8 | return x; 9 | } 10 | } -------------------------------------------------------------------------------- /csharp/1480-Running-Sum-Of-1D-Array.cs: -------------------------------------------------------------------------------- 1 | public class Solution 2 | { 3 | public int[] RunningSum(int[] nums) 4 | { 5 | for (int i = 1; i < nums.Length; i++) 6 | { 7 | nums[i] = nums[i - 1] + nums[i]; 8 | } 9 | return nums; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /csharp/152-Maximum-Product-Subarray.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int MaxProduct(int[] nums) { 3 | var maxProduct = nums.Max(); 4 | (int curMin, int curMax) = (1, 1); 5 | 6 | foreach(var n in nums) { 7 | var tmp = curMax * n; 8 | 9 | curMax = new int[] {n, n * curMin, n * curMax}.Max(); 10 | curMin = new int[] {n, n * curMin, tmp}.Min(); 11 | 12 | maxProduct = Math.Max(maxProduct, curMax); 13 | } 14 | 15 | return maxProduct; 16 | } 17 | } -------------------------------------------------------------------------------- /csharp/153-Find-Minimum-in-Rotated-Sorted-Array.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int FindMin(int[] nums) { 3 | int left = 0, right = nums.Length - 1; 4 | while (left <= right) { 5 | if (nums[left] <= nums[right]) { 6 | return nums[left]; 7 | } 8 | int mid = (left + right) / 2; 9 | if (nums[mid] >= nums[left]) { 10 | left = mid + 1; 11 | } 12 | else { 13 | right = mid; 14 | } 15 | } 16 | return 0; 17 | } 18 | } -------------------------------------------------------------------------------- /csharp/190-Reverse-Bits.cs: -------------------------------------------------------------------------------- 1 | public class Solution 2 | { 3 | public uint reverseBits(uint n) 4 | { 5 | uint result = 0; 6 | for (int i = 0; i < 32; i++) 7 | { 8 | uint temp = (n & 1); 9 | result = (result << 1) + temp; 10 | n >>= 1; 11 | } 12 | return result; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /csharp/191-Number-Of-1-Bits.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int HammingWeight(uint n) { 3 | var binary = Convert.ToString(n, 2); 4 | var hammingWeight = 0; 5 | for (int i = 0; i < binary.Length; i++) 6 | { 7 | hammingWeight += binary[i] - '0'; 8 | } 9 | return hammingWeight; 10 | } 11 | } -------------------------------------------------------------------------------- /csharp/198-House-Robber.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int Rob(int[] nums) { 3 | int rob1 = 0, rob2 = 0; 4 | 5 | foreach(var num in nums) { 6 | var temp = Math.Max(num + rob1, rob2); 7 | rob1 = rob2; 8 | rob2 = temp; 9 | } 10 | 11 | return rob2; 12 | } 13 | } -------------------------------------------------------------------------------- /csharp/217-Contains-Duplicate.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public bool ContainsDuplicate(int[] nums) { 3 | HashSet set = new HashSet(); 4 | 5 | foreach (int x in nums){ 6 | if (set.Contains(x)) return true; 7 | set.Add(x); 8 | } 9 | return false; 10 | } 11 | } -------------------------------------------------------------------------------- /csharp/238-Product-Of-Array-Except-Self.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] ProductExceptSelf(int[] nums) { 3 | int prefix = 1, postfix = 1; 4 | int[] res = new int[nums.Length]; 5 | 6 | for(int i = 0; i < nums.Length; i++){ 7 | res[i] = prefix; 8 | prefix *= nums[i]; 9 | } 10 | 11 | for(int i = nums.Length-1; i>=0; i--){ 12 | res[i] *= postfix; 13 | postfix *= nums[i]; 14 | } 15 | return res; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /csharp/252-Meeting-Rooms.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public bool CanAttendMeetings(int[][] intervals) { 3 | 4 | Array.Sort(intervals, (a, b) => a[0] < b[0] ? -1 : 1); 5 | for (int i = 1; i < intervals.Length; i++) 6 | { 7 | if (intervals[i][0] < intervals[i - 1][1]) 8 | { 9 | return false; 10 | } 11 | } 12 | return true; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /csharp/268-Missing-Number.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int MissingNumber(int[] nums) { 3 | int sum = 0; 4 | int total = nums.Length * (nums.Length + 1) / 2; 5 | for (int i = 0; i < nums.Length; i++) { 6 | sum += nums[i]; 7 | } 8 | return total - sum; 9 | } 10 | } -------------------------------------------------------------------------------- /csharp/309-Best-Time-to-Buy-and-Sell-Stock-With-Cooldown.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int MaxProfit(int[] prices) { 3 | int sold = 0, rest = 0, hold = Int32.MinValue; 4 | 5 | for (int i = 0; i < prices.Length; i++) { 6 | int prevSold = sold; 7 | sold = hold + prices[i]; 8 | hold = Math.Max(hold, rest - prices[i]); 9 | rest = Math.Max(rest, prevSold); 10 | } 11 | return Math.Max(sold, rest); 12 | } 13 | } -------------------------------------------------------------------------------- /csharp/322-Coin-Change.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int CoinChange(int[] coins, int amount) { 3 | var dp = Enumerable.Repeat(amount + 1, amount + 1).ToArray(); 4 | 5 | dp[0] = 0; 6 | 7 | for(var a = 1; a <= amount; a++) { 8 | foreach(var c in coins) { 9 | if(a - c >= 0) { 10 | dp[a] = Math.Min(dp[a], 1 + dp[a-c]); 11 | } 12 | } 13 | } 14 | 15 | return dp[amount] == amount + 1 16 | ? -1 17 | : dp[amount]; 18 | } 19 | } -------------------------------------------------------------------------------- /csharp/338-Counting-Bits.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] CountBits(int n) { 3 | var hammingWeights = new int[n+1]; 4 | for (int i = 0; i <= n; i++) 5 | { 6 | var binary = Convert.ToString(i, 2); 7 | var hammingWeight = 0; 8 | for (int j = 0; j < binary.Length; j++) 9 | { 10 | hammingWeight += binary[j] - '0'; 11 | } 12 | hammingWeights[i] = hammingWeight; 13 | } 14 | return hammingWeights; 15 | } 16 | } -------------------------------------------------------------------------------- /csharp/371-Sum-Of-Two-Integers.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int GetSum(int a, int b) { 3 | while (b != 0) 4 | { 5 | var carry = a & b; 6 | a = a ^ b; 7 | b = carry << 1; 8 | } 9 | return a; 10 | } 11 | } -------------------------------------------------------------------------------- /csharp/392-Is-Subsequence.cs: -------------------------------------------------------------------------------- 1 | public class Solution 2 | { 3 | public bool IsSubsequence(string s, string t) 4 | { 5 | int i = 0; 6 | int j = 0; 7 | while ((i < s.Length) && (j < t.Length)) 8 | { 9 | if (s[i] == t[j]) 10 | { 11 | i += 1; 12 | } 13 | j += 1; 14 | 15 | } 16 | if (i == s.Length) 17 | { 18 | return true; 19 | } 20 | else return false; 21 | } 22 | } -------------------------------------------------------------------------------- /csharp/45-Jump-Game-II.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int Jump(int[] nums) { 3 | int left = 0, right = 0, res = 0; 4 | 5 | while (right < nums.Length - 1) { 6 | int maxJump = 0; 7 | for (int i = left; i <= right; i++) { 8 | maxJump = Math.Max(maxJump, i + nums[i]); 9 | } 10 | left = right + 1; 11 | right = maxJump; 12 | res++; 13 | } 14 | return res; 15 | } 16 | } -------------------------------------------------------------------------------- /csharp/50-Pow(x, n).cs: -------------------------------------------------------------------------------- 1 | public class Solution 2 | { 3 | public double MyPow(double x, long n) 4 | { 5 | var result = helper(x, Math.Abs(n)); 6 | return n > 0 ? result : 1 / result; 7 | } 8 | 9 | private double helper(double x, long n) 10 | { 11 | if (x == 0) return 0; 12 | if (n == 0) return 1; 13 | 14 | var result = helper(x, n / 2); 15 | result = result * result; 16 | return n % 2 == 1 ? x * result : result; 17 | } 18 | } -------------------------------------------------------------------------------- /csharp/53-Maximum-Subarray.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int MaxSubArray(int[] nums) { 3 | int maxSub = nums[0]; 4 | int curSum = 0; 5 | 6 | for(int i = 0; i < nums.Length; i++){ 7 | if(curSum < 0){ 8 | curSum = 0; 9 | } 10 | curSum += nums[i]; 11 | maxSub = Math.Max(maxSub, curSum); 12 | } 13 | return maxSub; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /csharp/55-Jump-Game.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public bool CanJump(int[] nums) { 3 | int goal = nums.Length - 1; 4 | for (int i = nums.Length-1; i>=0; i--) 5 | { 6 | if (nums[i] + i >= goal) 7 | { 8 | goal = i; 9 | } 10 | } 11 | 12 | return goal == 0 ; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /csharp/62-Unique-Paths.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int UniquePaths(int m, int n) { 3 | var row = new int[n]; 4 | Array.Fill(row, 1); 5 | foreach (var i in Enumerable.Range(0, m - 1)) 6 | { 7 | var newRow = new int[n]; 8 | Array.Fill(newRow, 1); 9 | for (int j = n - 2; j >=0; j--) 10 | { 11 | newRow[j] = newRow[j + 1] + row[j]; 12 | } 13 | row = newRow; 14 | } 15 | return row[0]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /csharp/66-Plus-One.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] PlusOne(int[] digits) { 3 | string n = string.Join("", digits); 4 | n = (BigInteger.Parse(n) + 1).ToString(); 5 | int[] result = new int[n.Length]; 6 | for (int i = 0; i < n.Length; i++) 7 | { 8 | result[i] = n[i] - '0'; 9 | } 10 | return result; 11 | } 12 | } -------------------------------------------------------------------------------- /csharp/70-Climbing-Stairs.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int ClimbStairs(int n) { 3 | if(n <= 3) return n; 4 | int one = 2, two = 3; 5 | 6 | for(var i = 2; i < n - 1; i++) { 7 | (one, two) = (two, one + two); 8 | } 9 | 10 | return two; 11 | } 12 | } -------------------------------------------------------------------------------- /csharp/703-Kth-Largest-Element-In-A-Stream.cs: -------------------------------------------------------------------------------- 1 | public class KthLargest { 2 | PriorityQueue data = new PriorityQueue(); 3 | int k; 4 | 5 | public KthLargest(int k, int[] nums) { 6 | this.k = k; 7 | foreach(var num in nums) 8 | Add(num); 9 | } 10 | 11 | public int Add(int val) { 12 | data.Enqueue(val, val); 13 | 14 | if(data.Count > k) 15 | data.Dequeue(); 16 | 17 | return data.Peek(); 18 | } 19 | } -------------------------------------------------------------------------------- /csharp/704-Binary-Search.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int Search(int[] nums, int target) { 3 | int left = 0, right = nums.Length - 1; 4 | 5 | while (left <= right) { 6 | int mid = left + ((right - left) / 2); // (left + right) / 2 can lead to overflow 7 | if (nums[mid] > target) { 8 | right = mid - 1; 9 | } else if (nums[mid] < target) { 10 | left = mid + 1; 11 | } else { // Found the value 12 | return mid; 13 | } 14 | } 15 | return -1; 16 | } 17 | } -------------------------------------------------------------------------------- /go/1-Two-Sum.go: -------------------------------------------------------------------------------- 1 | func twoSum(nums []int, target int) []int { 2 | m := make(map[int]int) 3 | for idx, num := range nums { 4 | 5 | if val, found := m[target-num]; found { 6 | return []int{val, idx} 7 | } 8 | 9 | m[num] = idx 10 | } 11 | return nil 12 | } 13 | -------------------------------------------------------------------------------- /go/100-Same-Tree.go: -------------------------------------------------------------------------------- 1 | func isSameTree(p *TreeNode, q *TreeNode) bool { 2 | if p == nil && q == nil { 3 | return true 4 | } 5 | 6 | if p == nil || q == nil || p.Val != q.Val { 7 | return false 8 | } 9 | 10 | return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) 11 | } -------------------------------------------------------------------------------- /go/104-Maximum-Depth-of-Binary-Tree.go: -------------------------------------------------------------------------------- 1 | func maxDepth(root *TreeNode) int { 2 | if root == nil { 3 | return 0 4 | } 5 | 6 | left := maxDepth(root.Left) 7 | right := maxDepth(root.Right) 8 | 9 | if left > right { 10 | return 1 + left 11 | } 12 | 13 | return right + 1 14 | } -------------------------------------------------------------------------------- /go/11-Container-with-Most-Water.go: -------------------------------------------------------------------------------- 1 | func maxArea(height []int) int { 2 | left := 0 3 | right := len(height) - 1 4 | res := 0 5 | 6 | for left < right { 7 | area := min(height[left], height[right]) * (right - left) 8 | 9 | if area > res { 10 | res = area 11 | } 12 | 13 | if height[left] > height[right] { 14 | right-- 15 | } else { 16 | left++ 17 | } 18 | } 19 | 20 | return res 21 | } 22 | 23 | func min(a, b int) int { 24 | if a < b { 25 | return a 26 | } 27 | return b 28 | } -------------------------------------------------------------------------------- /go/110-Balanced-Binary-Tree.go: -------------------------------------------------------------------------------- 1 | func isBalanced(root *TreeNode) bool { 2 | return isBalancedUtil(root) != math.MaxUint32 3 | } 4 | 5 | func isBalancedUtil(root *TreeNode) int { 6 | if root == nil { 7 | return 0 8 | } 9 | 10 | left := isBalancedUtil(root.Left) 11 | right := isBalancedUtil(root.Right) 12 | 13 | if left == math.MaxUint32 || right == math.MaxUint32 { 14 | return math.MaxUint32 15 | } 16 | 17 | if math.Abs(float64(left-right)) > 1 { 18 | return math.MaxUint32 19 | } 20 | 21 | if left > right { 22 | return left + 1 23 | } 24 | 25 | return right + 1 26 | } -------------------------------------------------------------------------------- /go/121-Best-Time-To-Buy-And-Sell-Stock.go: -------------------------------------------------------------------------------- 1 | func maxProfit(prices []int) int { 2 | min := math.MaxUint32 3 | res := 0 4 | 5 | for _, price := range prices { 6 | if price > min { 7 | if price-min > res { 8 | res = price - min 9 | } 10 | } else { 11 | min = price 12 | } 13 | } 14 | 15 | return res 16 | } -------------------------------------------------------------------------------- /go/128-Longest-Consecutive-Sequence.go: -------------------------------------------------------------------------------- 1 | func longestConsecutive(nums []int) int { 2 | set := map[int]bool{} 3 | 4 | for _, num := range nums { 5 | set[num] = true 6 | } 7 | 8 | res := 0 9 | 10 | for _, num := range nums { 11 | if set[num-1] { 12 | continue 13 | } 14 | 15 | sequence := 1 16 | temp := num + 1 17 | 18 | for set[temp] { 19 | sequence++ 20 | temp++ 21 | } 22 | 23 | if sequence > res { 24 | res = sequence 25 | } 26 | } 27 | 28 | return res 29 | } -------------------------------------------------------------------------------- /go/13-Roman-To-Integer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func romanToInt(s string) int { 4 | letters := map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} 5 | length := len(s) 6 | var ans int 7 | for i := 0; i < length; i++ { 8 | if i+1 < length && letters[s[i]] < letters[s[i+1]] { 9 | ans -= letters[s[i]] 10 | } else { 11 | ans += letters[s[i]] 12 | } 13 | } 14 | return ans 15 | } 16 | -------------------------------------------------------------------------------- /go/134-Gas-Station.go: -------------------------------------------------------------------------------- 1 | func canCompleteCircuit(gas []int, cost []int) int { 2 | sumGas := 0 3 | sumCost := 0 4 | 5 | for idx, _ := range gas { 6 | sumGas += gas[idx] 7 | sumCost += cost[idx] 8 | } 9 | 10 | if sumGas < sumCost { 11 | return -1 12 | } 13 | 14 | res := 0 15 | total := 0 16 | 17 | for idx, _ := range gas { 18 | total += gas[idx] - cost[idx] 19 | 20 | if total < 0 { 21 | total = 0 22 | res = idx + 1 23 | } 24 | } 25 | 26 | return res 27 | } -------------------------------------------------------------------------------- /go/136-Single-Number.go: -------------------------------------------------------------------------------- 1 | func singleNumber(nums []int) int { 2 | res := 0 3 | 4 | for _, num := range nums { 5 | res ^= num 6 | } 7 | 8 | return res 9 | } -------------------------------------------------------------------------------- /go/141-Linked-List-Cycle.go: -------------------------------------------------------------------------------- 1 | func hasCycle(head *ListNode) bool { 2 | if head == nil || head.Next == nil { 3 | return false 4 | } 5 | slow := head 6 | fast := head 7 | for fast != nil && fast.Next != nil { 8 | slow = slow.Next 9 | fast = fast.Next.Next 10 | if slow == fast { 11 | return true 12 | } 13 | } 14 | return false 15 | } 16 | -------------------------------------------------------------------------------- /go/153-Find-Minimum-in-Rotated-Sorted-Array.go: -------------------------------------------------------------------------------- 1 | func findMin(nums []int) int { 2 | res := nums[0] 3 | l, r := 0, len(nums)-1 4 | 5 | for l <= r { 6 | p := (l+r) / 2 7 | if nums[p] >= nums[0] { 8 | l = p+1 9 | } else { 10 | if nums[p] < res { 11 | res = nums[p] 12 | } 13 | r = p-1 14 | } 15 | } 16 | 17 | return res 18 | } 19 | -------------------------------------------------------------------------------- /go/167-Two-Sum-II.go: -------------------------------------------------------------------------------- 1 | func twoSum(numbers []int, target int) []int { 2 | p1 := 0 3 | p2 := len(numbers) - 1 4 | 5 | for p1 < p2 { 6 | n := numbers[p1] + numbers[p2] 7 | if n == target { 8 | return []int{p1 + 1, p2 + 1} 9 | } 10 | 11 | if n > target { 12 | p2-- 13 | }else{ 14 | p1++ 15 | } 16 | } 17 | 18 | return []int{0,0} 19 | } 20 | -------------------------------------------------------------------------------- /go/190-Reverse-Bits.go: -------------------------------------------------------------------------------- 1 | func reverseBits(num uint32) uint32 { 2 | var res uint32 = 0 3 | for i := 0; i < 32; i++ { 4 | bit := (num >> i) & 1 5 | res = res | (bit << (31 - i)) 6 | } 7 | return res 8 | } -------------------------------------------------------------------------------- /go/191-Number-of-1-Bits.go: -------------------------------------------------------------------------------- 1 | func hammingWeight(num uint32) int { 2 | res := 0 3 | for num > 0 { 4 | num &= num - 1 5 | res += 1 6 | } 7 | return res 8 | } -------------------------------------------------------------------------------- /go/198-House-Robber.go: -------------------------------------------------------------------------------- 1 | func rob(nums []int) int { 2 | dp := make([] int, len(nums)+2) 3 | 4 | for i := 2; i < len(dp); i++ { 5 | if dp[i-1] > dp[i-2] + nums[i-2] { 6 | dp[i] = dp[i-1] 7 | } else { 8 | dp[i] = dp[i-2] + nums[i-2] 9 | } 10 | } 11 | 12 | return dp[len(dp)-1] 13 | } -------------------------------------------------------------------------------- /go/20-Valid-Parentheses.go: -------------------------------------------------------------------------------- 1 | func isValid(s string) bool { 2 | pairs := map[byte]byte{ 3 | '}': '{', 4 | ']': '[', 5 | ')': '(', 6 | } 7 | 8 | stack := make([]byte, 0) 9 | 10 | for _, char := range []byte(s) { 11 | pair, ok := pairs[char] 12 | if !ok { 13 | stack = append(stack, char) 14 | continue 15 | } 16 | 17 | if len(stack) == 0 { 18 | return false 19 | } 20 | 21 | if stack[len(stack) - 1] != pair { 22 | return false 23 | } 24 | 25 | stack = stack[:len(stack) - 1] 26 | } 27 | 28 | return len(stack) == 0 29 | } 30 | -------------------------------------------------------------------------------- /go/217-Contains-Duplicate.go: -------------------------------------------------------------------------------- 1 | func containsDuplicate(nums []int) bool { 2 | nums_map := map[int]int{} 3 | for _, n := range nums { 4 | if _, ok := nums_map[n]; !ok { 5 | nums_map[n] = 1 6 | } else { 7 | return true 8 | } 9 | } 10 | return false 11 | 12 | } -------------------------------------------------------------------------------- /go/226-Invert-Binary-Tree.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * type TreeNode struct { 4 | * Val int 5 | * Left *TreeNode 6 | * Right *TreeNode 7 | * } 8 | */ 9 | func invertTree(root *TreeNode) *TreeNode { 10 | if root == nil { 11 | return root 12 | } 13 | 14 | left := invertTree(root.Left) 15 | root.Left = invertTree(root.Right) 16 | root.Right = left 17 | 18 | return root 19 | } -------------------------------------------------------------------------------- /go/230-Kth-Smallest-Element-in-a-BST.go: -------------------------------------------------------------------------------- 1 | func kthSmallest(root *TreeNode, k int) int { 2 | stack := make([]*TreeNode, 0, k) 3 | 4 | for { 5 | for root != nil { 6 | stack = append(stack, root) 7 | root = root.Left 8 | } 9 | 10 | root = stack[len(stack) - 1] 11 | stack = stack[:len(stack) - 1] 12 | 13 | k-- 14 | if k == 0 { 15 | return root.Val 16 | } 17 | 18 | root = root.Right 19 | } 20 | 21 | return -1 22 | } 23 | -------------------------------------------------------------------------------- /go/235-Lowest-Common-Ancestor-Of-BST.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * type TreeNode struct { 4 | * Val int 5 | * Left *TreeNode 6 | * Right *TreeNode 7 | * } 8 | */ 9 | 10 | func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { 11 | if p.Val > root.Val && q.Val > root.Val { 12 | return lowestCommonAncestor(root.Right, p, q) 13 | } 14 | 15 | if p.Val < root.Val && q.Val < root.Val { 16 | return lowestCommonAncestor(root.Left, p, q) 17 | } 18 | 19 | return root 20 | } 21 | -------------------------------------------------------------------------------- /go/236-Lowest-Common-Ancestor-of-Binary-Tree.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * type TreeNode struct { 4 | * Val int 5 | * Left *TreeNode 6 | * Right *TreeNode 7 | * } 8 | */ 9 | func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { 10 | if root == nil || p == root || q == root { 11 | return root 12 | } 13 | 14 | left := lowestCommonAncestor(root.Left, p, q) 15 | right := lowestCommonAncestor(root.Right, p, q) 16 | 17 | if left == nil { 18 | return right 19 | } 20 | 21 | if right == nil { 22 | return left 23 | } 24 | 25 | return root 26 | } -------------------------------------------------------------------------------- /go/238-Product-Of-Array-Except-Self.go: -------------------------------------------------------------------------------- 1 | func productExceptSelf(nums []int) []int { 2 | res := make([]int, len(nums)) 3 | for i := 0; i < len(res); i++ { 4 | res[i] = 1 5 | } 6 | 7 | prefix := 1 8 | for i := 0; i < len(nums); i++ { 9 | res[i] = prefix 10 | prefix *= nums[i] 11 | } 12 | 13 | postfix := 1 14 | for i := len(nums) - 1; i >= 0; i-- { 15 | res[i] *= postfix 16 | postfix *= nums[i] 17 | } 18 | 19 | return res 20 | } -------------------------------------------------------------------------------- /go/24-Swap-Nodes-in-Pairs.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * type ListNode struct { 4 | * Val int 5 | * Next *ListNode 6 | * } 7 | */ 8 | func swapPairs(head *ListNode) *ListNode { 9 | if head == nil || head.Next == nil { 10 | return head 11 | } 12 | 13 | next := head.Next 14 | swapped := swapPairs(next.Next) 15 | 16 | next.Next, head.Next = head, swapped 17 | 18 | return next 19 | } -------------------------------------------------------------------------------- /go/242-Valid-Anagram.go: -------------------------------------------------------------------------------- 1 | func isAnagram(s string, t string) bool { 2 | if len(s) != len(t) { 3 | return false 4 | } 5 | 6 | var freq [26]int 7 | 8 | for idx := 0; idx < len(s); idx++ { 9 | freq[s[idx] - 'a']++ 10 | freq[t[idx] - 'a']-- 11 | } 12 | 13 | for idx := 0; idx < len(freq); idx++ { 14 | if freq[idx] != 0 { 15 | return false 16 | } 17 | } 18 | 19 | return true 20 | } -------------------------------------------------------------------------------- /go/26-Remove-Duplicates-From-Sorted-Array.go: -------------------------------------------------------------------------------- 1 | func removeDuplicates(nums []int) int { 2 | length := len(nums) 3 | if length < 2 { 4 | return length 5 | } 6 | k, i := 1, 1 7 | for i < length { 8 | if nums[i] != nums[i-1] { 9 | nums[k] = nums[i] 10 | k++ 11 | } 12 | i++ 13 | } 14 | return k 15 | } 16 | -------------------------------------------------------------------------------- /go/268-Missing-Number.go: -------------------------------------------------------------------------------- 1 | func missingNumber(nums []int) int { 2 | res := len(nums) 3 | 4 | for i := 0; i < len(nums); i++ { 5 | res += i - nums[i] 6 | } 7 | return res 8 | } -------------------------------------------------------------------------------- /go/27-Remove-Element.go: -------------------------------------------------------------------------------- 1 | func removeElement(nums []int, val int) int { 2 | left, right := 0, len(nums)-1 3 | 4 | for left <= right { 5 | if nums[left] == val { 6 | nums[left], nums[right] = nums[right], nums[left] 7 | right-- 8 | } else { 9 | left++ 10 | } 11 | } 12 | 13 | return left 14 | } -------------------------------------------------------------------------------- /go/287-Find-the-Duplicate-Number.go: -------------------------------------------------------------------------------- 1 | func findDuplicate(nums []int) int { 2 | slow, fast := nums[0], nums[nums[0]] 3 | 4 | for slow != fast { 5 | slow = nums[slow] 6 | fast = nums[nums[fast]] 7 | } 8 | 9 | slow = 0 10 | for slow != fast { 11 | slow = nums[slow] 12 | fast = nums[fast] 13 | } 14 | return slow 15 | } -------------------------------------------------------------------------------- /go/3-Longest-Substring-Without-Repeating-Characters.go: -------------------------------------------------------------------------------- 1 | func lengthOfLongestSubstring(s string) int { 2 | charSet := make(map[byte]bool) 3 | l := 0 4 | res := 0 5 | 6 | for r, _ := range s { 7 | for charSet[s[r]] { 8 | delete(charSet,s[l]) 9 | l++ 10 | } 11 | charSet[s[r]] = true 12 | res = max(res, r-l+1) 13 | } 14 | return res 15 | } 16 | 17 | func max(a,b int) int { 18 | if a > b{ 19 | return a 20 | } 21 | return b 22 | } 23 | -------------------------------------------------------------------------------- /go/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.go: -------------------------------------------------------------------------------- 1 | func maxProfit(prices []int) int { 2 | sold, hold, rest := 0, math.MinInt32, 0 3 | 4 | for i := 0; i < len(prices); i++ { 5 | prevSold := sold 6 | sold = hold + prices[i] 7 | hold = max(hold, rest - prices[i]) 8 | rest = max(rest, prevSold) 9 | } 10 | return max(sold, rest) 11 | } 12 | 13 | // Golang does not have a built-in max for integers 14 | func max(a int, b int) int { 15 | if (a > b) { 16 | return a 17 | } 18 | return b 19 | } -------------------------------------------------------------------------------- /go/338-Counting-Bits.go: -------------------------------------------------------------------------------- 1 | func countBits(n int) []int { 2 | dp := make([]int, n + 1) 3 | offset := 1 4 | 5 | for i := 1; i <= n; i++ { 6 | if offset * 2 == i { 7 | offset = i 8 | } 9 | dp[i] = 1 + dp[i - offset] 10 | } 11 | return dp 12 | } -------------------------------------------------------------------------------- /go/371-Sum-of-Two-Integers.go: -------------------------------------------------------------------------------- 1 | func getSum(a int, b int) int { 2 | for b != 0 { 3 | temp := (a & b) << 1 4 | a = (a ^ b) 5 | b = temp 6 | } 7 | return a 8 | } -------------------------------------------------------------------------------- /go/45-Jump-Game-II.go: -------------------------------------------------------------------------------- 1 | func jump(nums []int) int { 2 | step, end, max := 0, 0, 0 3 | 4 | for i := 0; i < len(nums)-1; i++ { 5 | if i + nums[i] > max { 6 | max = i+nums[i] 7 | } 8 | 9 | if i == end { 10 | step++; 11 | end = max 12 | } 13 | } 14 | 15 | return step 16 | } -------------------------------------------------------------------------------- /go/46-Permutations.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func permute(nums []int) [][]int { 4 | n := len(nums) 5 | ans := make([][]int, 0) 6 | curr := make([]int, 0, n) 7 | vis := make(map[int]int) 8 | var backtrack func(idx int) 9 | backtrack = func(idx int) { 10 | if len(curr) == n { 11 | ans = append(ans, append([]int{}, curr...)) 12 | } 13 | for i := 0; i < n; i++ { 14 | if vis[i] == 0 { 15 | vis[i]++ 16 | curr = append(curr, nums[i]) 17 | backtrack(i + 1) 18 | curr = curr[:len(curr)-1] 19 | vis[i]-- 20 | } 21 | } 22 | } 23 | backtrack(0) 24 | return ans 25 | } 26 | -------------------------------------------------------------------------------- /go/53-Maximum-Subarray.go: -------------------------------------------------------------------------------- 1 | func maxSubArray(nums []int) int { 2 | result, total := nums[0], 0 3 | 4 | for i := 0; i < len(nums); i++ { 5 | total += nums[i] 6 | result = max(result, total) 7 | if total < 0 { 8 | total = 0 9 | } 10 | } 11 | return result 12 | } 13 | 14 | // Golang does not have a built-in max for integers 15 | func max(a int, b int) int { 16 | if a > b { 17 | return a 18 | } 19 | return b 20 | } -------------------------------------------------------------------------------- /go/55-Jump-Game.go: -------------------------------------------------------------------------------- 1 | func canJump(nums []int) bool { 2 | goal := len(nums) - 1 3 | 4 | for i := len(nums) - 2; i >= 0; i-- { 5 | if i + nums[i] >= goal { 6 | goal = i 7 | } 8 | } 9 | return goal == 0 10 | } -------------------------------------------------------------------------------- /go/62-Unique-Paths.go: -------------------------------------------------------------------------------- 1 | func uniquePaths(m int, n int) int { 2 | dp := make([]int, n) 3 | dp[0] = 1 4 | 5 | for i := 0; i < m; i++ { 6 | for j := 1; j < n; j++ { 7 | dp[j] += dp[j-1] 8 | } 9 | } 10 | 11 | return dp[n-1] 12 | } -------------------------------------------------------------------------------- /go/66-Plus-One.go: -------------------------------------------------------------------------------- 1 | func plusOne(digits []int) []int { 2 | for i := len(digits) - 1; i >= 0; i-- { 3 | if digits[i] < 9 { 4 | digits[i] += 1 5 | return digits 6 | } 7 | digits[i] = 0 8 | } 9 | digits[0] = 1 10 | digits = append(digits, 0) 11 | return digits 12 | } -------------------------------------------------------------------------------- /go/7-Reverse-Integer.go: -------------------------------------------------------------------------------- 1 | func reverse(x int) int { 2 | negative := x < 0 3 | num := 0 4 | 5 | if negative { 6 | x = -x 7 | } 8 | 9 | for x > 0 { 10 | if math.MaxInt32/10 < num { 11 | return 0 12 | } 13 | 14 | num = 10*num + x%10 15 | x /= 10 16 | } 17 | 18 | if negative { 19 | return -num 20 | } 21 | 22 | return num 23 | } -------------------------------------------------------------------------------- /go/70-Climbing-Stairs.go: -------------------------------------------------------------------------------- 1 | func climbStairs(n int) int { 2 | one, two := 1, 1 3 | 4 | for i := 0; i < n-1; i++ { 5 | sum := one + two 6 | one, two = two, sum 7 | } 8 | 9 | return two 10 | } -------------------------------------------------------------------------------- /go/704-Binary-Search.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func search(nums []int, target int) int { 4 | left := 0 5 | right := len(nums) - 1 6 | 7 | for left <= right { 8 | middle := (left + right) / 2 9 | 10 | if nums[middle] == target { 11 | return middle 12 | } else if nums[middle] < target { 13 | left = middle + 1 14 | } else { 15 | right = middle - 1 16 | } 17 | } 18 | return -1 19 | 20 | } 21 | -------------------------------------------------------------------------------- /go/746-Min-Cost-Climbing-Stairs.go: -------------------------------------------------------------------------------- 1 | func minCostClimbingStairs(cost []int) int { 2 | n := len(cost) 3 | dp := make([]int, n+1) 4 | 5 | if n == 2 { 6 | return min(cost[0], cost[1]) 7 | } 8 | 9 | for i := 2; i <= n; i++ { 10 | a := dp[i-1] + cost[i-1] 11 | b := dp[i-2] + cost[i-2] 12 | 13 | dp[i] = min(a, b) 14 | } 15 | 16 | return dp[n] 17 | } 18 | 19 | func min(x, y int) int { 20 | if x > y { 21 | return y 22 | } 23 | 24 | return x 25 | } -------------------------------------------------------------------------------- /go/75-Sort-Colors.go: -------------------------------------------------------------------------------- 1 | func sortColors(nums []int) { 2 | low, mid, hi := 0, 0, len(nums)-1 3 | 4 | for low <= hi { 5 | if nums[low] == 2 { 6 | nums[low], nums[hi] = nums[hi], nums[low] 7 | hi-- 8 | } else if nums[low] == 0 { 9 | nums[low], nums[mid] = nums[mid], nums[low] 10 | mid++ 11 | low++ 12 | } else { 13 | low++ 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /go/763-Partition-Labels.go: -------------------------------------------------------------------------------- 1 | func partitionLabels(s string) []int { 2 | mapCharToIndex := map[byte]int{} 3 | 4 | for idx := 0; idx < len(s); idx++ { 5 | mapCharToIndex[s[idx]] = idx 6 | } 7 | 8 | st, lastIdx := 0, 0 9 | res := []int{} 10 | 11 | for end := 0; end < len(s); end++ { 12 | curr := s[end] 13 | idx := mapCharToIndex[curr] 14 | 15 | if idx > lastIdx { 16 | lastIdx = idx 17 | } 18 | 19 | if end == lastIdx { 20 | res = append(res, lastIdx-st+1) 21 | st = lastIdx + 1 22 | } 23 | } 24 | 25 | return res 26 | } -------------------------------------------------------------------------------- /go/78-Subsets.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func subsets(nums []int) [][]int { 4 | ans := make([][]int, 0) 5 | curr := make([]int, 0) 6 | var backtrack func(idx int) 7 | backtrack = func(idx int) { 8 | ans = append(ans, append([]int{}, curr...)) 9 | if idx == len(nums) { 10 | return 11 | } 12 | for i := idx; i < len(nums); i++ { 13 | curr = append(curr, nums[i]) 14 | backtrack(i + 1) 15 | curr = curr[:len(curr)-1] 16 | } 17 | } 18 | backtrack(0) 19 | return ans 20 | } 21 | -------------------------------------------------------------------------------- /go/83-Remove-Duplicates-from-Sorted-List.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * type ListNode struct { 4 | * Val int 5 | * Next *ListNode 6 | * } 7 | */ 8 | func deleteDuplicates(head *ListNode) *ListNode { 9 | if head == nil || head.Next == nil { 10 | return head 11 | } 12 | 13 | prev, curr := head, head.Next 14 | 15 | for curr != nil { 16 | for curr != nil && curr.Val == prev.Val { 17 | curr = curr.Next 18 | prev.Next = curr 19 | } 20 | 21 | if curr != nil { 22 | prev, curr = curr, curr.Next 23 | } 24 | } 25 | 26 | return head 27 | } -------------------------------------------------------------------------------- /go/852-Peak-Index-In-A-Mountain-Array.go: -------------------------------------------------------------------------------- 1 | func peakIndexInMountainArray(arr []int) int { 2 | left, right := 0, len(arr)-1 3 | res := -1 4 | 5 | for left <= right { 6 | mid := left + (right-left+1)/2 7 | 8 | if arr[mid-1] <= arr[mid] { 9 | left, res = mid+1, mid 10 | } else { 11 | right = mid - 1 12 | } 13 | } 14 | 15 | return res 16 | } -------------------------------------------------------------------------------- /go/876-Middle-Of-The-Linked-List.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * type ListNode struct { 4 | * Val int 5 | * Next *ListNode 6 | * } 7 | */ 8 | func middleNode(head *ListNode) *ListNode { 9 | if head == nil || head.Next == nil { 10 | return head 11 | } 12 | 13 | slow, fast := head, head 14 | 15 | for fast != nil && fast.Next != nil { 16 | slow, fast = slow.Next, fast.Next.Next 17 | } 18 | 19 | return slow 20 | } 21 | -------------------------------------------------------------------------------- /go/98-Validate-Binary-Search-Tree.go: -------------------------------------------------------------------------------- 1 | func isValidBST(root *TreeNode) bool { 2 | return isValid(root, nil, nil) 3 | } 4 | 5 | func isValid(root, min, max *TreeNode) bool { 6 | if root == nil { 7 | return true 8 | } 9 | 10 | if min != nil && root.Val <= min.Val { 11 | return false 12 | } 13 | 14 | if max != nil && root.Val >= max.Val { 15 | return false 16 | } 17 | 18 | return isValid(root.Left, min, root) && isValid(root.Right, root, max) 19 | } -------------------------------------------------------------------------------- /java/1-Two-Sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int[] twoSum(int[] nums, int target) { 4 | HashMap prevMap = new HashMap<>(); 5 | 6 | for (int i = 0; i < nums.length; i++) { 7 | int num = nums[i]; 8 | int diff = target - num; 9 | 10 | if (prevMap.containsKey(nums[i])) { 11 | return new int[] { prevMap.get(num), i }; 12 | } 13 | 14 | prevMap.put(diff, i); 15 | } 16 | 17 | return new int[] {}; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /java/104-Maximum-Depth-of-Binary-Tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int maxDepth(TreeNode root) { 4 | if (root == null) return 0; 5 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /java/1046-Last-Stone-Weight.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int lastStoneWeight(int[] stones) { 4 | PriorityQueue maxHeap = new PriorityQueue(); 5 | for (int stone : stones) maxHeap.add(-stone); 6 | while (maxHeap.size() > 1) { 7 | int stone1 = maxHeap.remove(); 8 | int stone2 = maxHeap.remove(); 9 | if (stone1 != stone2) maxHeap.add(stone1 - stone2); 10 | } 11 | return maxHeap.size() != 0 ? (-maxHeap.remove()) : 0; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /java/121-Best-Time-to-Buy-and-Sell-Stock.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int maxProfit(int[] prices) { 4 | int left = 0; 5 | int right = 1; 6 | int maxProfit = 0; 7 | while (right < prices.length) { 8 | if (prices[left] < prices[right]) { 9 | maxProfit = Math.max(maxProfit, prices[right] - prices[left]); 10 | right++; 11 | } else { 12 | left = right; 13 | right++; 14 | } 15 | } 16 | return maxProfit; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/133-Clone-Graph.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public HashMap map = new HashMap<>(); 4 | 5 | public Node cloneGraph(Node node) { 6 | if (node == null) return null; 7 | if (map.containsKey(node.val)) return map.get(node.val); 8 | Node newNode = new Node(node.val, new ArrayList()); 9 | map.put(node.val, newNode); 10 | for (Node neighbor : node.neighbors) { 11 | newNode.neighbors.add(cloneGraph(neighbor)); 12 | } 13 | return newNode; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/136-Single-Number.java: -------------------------------------------------------------------------------- 1 | //We can use xor operation as it cancel out itself (i.e. only when values are different in binary representation then give output). See how xor operation works if confused. 2 | class Solution { 3 | 4 | public int singleNumber(int[] nums) { 5 | int ans = nums[0]; 6 | for (int i = 1; i < nums.length; i++) ans ^= nums[i]; 7 | return ans; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /java/138-Copy-List-with-Random-Pointer.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public Node copyRandomList(Node head) { 4 | Node cur = head; 5 | HashMap map = new HashMap<>(); 6 | while (cur != null) { 7 | map.put(cur, new Node(cur.val)); 8 | cur = cur.next; 9 | } 10 | cur = head; 11 | while (cur != null) { 12 | map.get(cur).next = map.get(cur.next); 13 | map.get(cur).random = map.get(cur.random); 14 | cur = cur.next; 15 | } 16 | return map.get(head); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/141. Linked List Cycle.java: -------------------------------------------------------------------------------- 1 | //Fast and slow pointer 2 | 3 | public class Solution { 4 | 5 | public boolean hasCycle(ListNode head) { 6 | ListNode fast = head; 7 | ListNode slow = head; 8 | while (fast != null && fast.next != null) { 9 | fast = fast.next.next; 10 | slow = slow.next; 11 | if (fast == slow) return true; 12 | } 13 | return false; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/1448-Count-Good-Nodes-in-Binary-Tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int goodNodes(TreeNode root) { 4 | return helper(root, -99999); 5 | } 6 | 7 | public int helper(TreeNode root, int max) { 8 | if (root == null) return 0; 9 | 10 | int res = root.val >= max ? 1 : 0; 11 | 12 | res += helper(root.left, Math.max(root.val, max)); 13 | res += helper(root.right, Math.max(root.val, max)); 14 | 15 | return res; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/152-Maximum-Product-Subarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int maxProduct(int[] nums) { 4 | if (nums.length == 1) return nums[0]; 5 | 6 | int res = nums[0]; 7 | int max = 1; 8 | int min = 1; 9 | 10 | for (int n : nums) { 11 | int tmp = max * n; 12 | max = Math.max(n, Math.max(tmp, min * n)); 13 | min = Math.min(n, Math.min(tmp, min * n)); 14 | res = Math.max(res, max); 15 | } 16 | return res; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/153-Find-Minimum-in-Rotated-Sorted-Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int findMin(int[] nums) { 4 | int l = 0; 5 | int r = nums.length - 1; 6 | 7 | while (l <= r) { 8 | if (nums[l] <= nums[r]) { 9 | return nums[l]; 10 | } 11 | 12 | int mid = (l + r) / 2; 13 | if (nums[mid] >= nums[l]) { 14 | l = mid + 1; 15 | } else { 16 | r = mid; 17 | } 18 | } 19 | return 0; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java/162. Find Peak Element: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findPeakElement(int[] nums) { 3 | int pi=0; 4 | if(nums.length==1) 5 | return 0; 6 | if(nums[0]>nums[1]){ 7 | pi=0; 8 | } 9 | for(int i=1;i=nums[i-1] && nums[i]>=nums[i+1]){ 11 | pi=i; 12 | } 13 | } 14 | if(nums[nums.length-1]>nums[nums.length-2]){ 15 | pi=nums.length-1; 16 | } 17 | return pi; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /java/1899-Merge-Triplets-To-Form-Target-Triplet.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public boolean mergeTriplets(int[][] triplets, int[] target) { 4 | boolean[] greedy = new boolean[3]; 5 | loop:for (int[] triplet : triplets) { 6 | for (int i = 0; i < 3; i++) if ( 7 | triplet[i] > target[i] 8 | ) continue loop; 9 | 10 | for (int i = 0; i < 3; i++) if (triplet[i] == target[i]) greedy[i] = 11 | true; 12 | } 13 | 14 | return greedy[0] && greedy[1] && greedy[2]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/190-Reverse-Bits.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | // you need treat n as an unsigned value 4 | public int reverseBits(int n) { 5 | int ans = 0; 6 | 7 | for (int i = 0; i < 32; i++) { 8 | ans <<= 1; 9 | ans |= (n & 1); 10 | n >>= 1; 11 | } 12 | return ans; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/217-Contains-Duplicate.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public boolean containsDuplicate(int[] nums) { 4 | Set uniques = new HashSet<>(); 5 | for (int i = 0; i < nums.length; i++) { 6 | if (uniques.contains(nums[i])) { 7 | return true; 8 | } 9 | uniques.add(nums[i]); 10 | } 11 | return false; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /java/226-Invert-Binary-Tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public TreeNode invertTree(TreeNode root) { 4 | if (root == null) return null; 5 | TreeNode node = new TreeNode(root.val); 6 | node.right = invertTree(root.left); 7 | node.val = root.val; 8 | node.left = invertTree(root.right); 9 | return node; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /java/237-delete-node-in-a-linked-list: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public void deleteNode(ListNode node) { 11 | node.val = node.next.val; 12 | node.next = node.next.next; 13 | return; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/237-delete-node-in-a-linked-list.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public void deleteNode(ListNode node) { 11 | node.val = node.next.val; 12 | node.next = node.next.next; 13 | return; 14 | } 15 | } -------------------------------------------------------------------------------- /java/242-Valid-Anagram.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public boolean isAnagram(String s, String t) { 4 | char sarr[]=s.toCharArray(); 5 | char tarr[]=t.toCharArray(); 6 | 7 | Arrays.sort(sarr); 8 | Arrays.sort(tarr); 9 | 10 | if(Arrays.equals(sarr,tarr)){ 11 | return true; 12 | }else{ 13 | return false; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/268-Missing-Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int missingNumber(int[] nums) { 4 | int sum = 0; 5 | int total = nums.length * (nums.length + 1) / 2; 6 | for (int i = 0; i < nums.length; i++) { 7 | sum += nums[i]; 8 | } 9 | return total - sum; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /java/338-Counting-Bits.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int[] countBits(int n) { 4 | int[] ans = new int[n + 1]; 5 | 6 | for (int i = 0; i <= n; i++) { 7 | ans[i] = count(i); 8 | } 9 | return ans; 10 | } 11 | 12 | private int count(int x) { 13 | int count = 0; 14 | while (x != 0) { 15 | x &= x - 1; 16 | count++; 17 | } 18 | return count; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java/342-Power-of-Four.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public boolean isPowerOfFour(int n) { 4 | double x = Math.log(n) / Math.log(4); 5 | return x == (int) x; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /java/371-Sum-of-Two-Integers.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int getSum(int a, int b) { 4 | while (b != 0) { 5 | int tmp = (a & b) << 1; 6 | a = (a ^ b); 7 | b = tmp; 8 | } 9 | return a; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /java/45-Jump-game-II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int jump(int[] nums) { 4 | int res = 0, r = 0, l = 0, fur = 0; 5 | 6 | while (r < nums.length - 1) { 7 | fur = 0; 8 | for (int i = l; i <= r; i++) fur = Math.max(fur, i + nums[i]); 9 | l = r + 1; 10 | r = fur; 11 | res++; 12 | } 13 | return res; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/53-Maximum-Subarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int maxSubArray(int[] nums) { 4 | if (nums.length == 1) return nums[0]; 5 | 6 | int sum = 0; 7 | int max = Integer.MIN_VALUE; 8 | 9 | for (int n : nums) { 10 | sum += n; 11 | max = Math.max(max, sum); 12 | 13 | if (sum < 0) { 14 | sum = 0; 15 | } 16 | } 17 | return max; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /java/543-Diameter-of-Binary-Tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | int result = -1; 4 | 5 | public int diameterOfBinaryTree(TreeNode root) { 6 | dfs(root); 7 | return result; 8 | } 9 | 10 | private int dfs(TreeNode current) { 11 | if (current == null) { 12 | return -1; 13 | } 14 | int left = 1 + dfs(current.left); 15 | int right = 1 + dfs(current.right); 16 | result = Math.max(result, (left + right)); 17 | return Math.max(left, right); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /java/55-Jump-Game.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public boolean canJump(int[] nums) { 4 | int goal = nums.length - 1; 5 | for (int i = nums.length - 2; i >= 0; i--) { 6 | if (nums[i] + i >= goal) { 7 | goal = i; 8 | } 9 | } 10 | return goal == 0; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /java/560-Subarray-Sum-Equals-K.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int subarraySum(int[] nums, int k) { 4 | int res = 0, sum = 0; 5 | HashMap map = new HashMap(); 6 | map.put(0, 1); 7 | for (int i = 0; i < nums.length; i++) { 8 | sum += nums[i]; 9 | int diff = sum - k; 10 | if (map.containsKey(diff)) { 11 | res += map.get(diff); 12 | } 13 | map.put(sum, map.getOrDefault(sum, 0) + 1); 14 | } 15 | return res; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/7-Reverse-Integer.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int reverse(int x) { 3 | boolean negative = false; 4 | long revInt = 0; 5 | 6 | if(x < 0) { 7 | negative = true; 8 | x = -x; 9 | } 10 | 11 | while(x > 0){ 12 | revInt = (10*revInt) + (x % 10); 13 | x /= 10; 14 | } 15 | if(revInt < Integer.MIN_VALUE || revInt > Integer.MAX_VALUE) return 0; 16 | if(negative) return (int) -revInt; else return (int) revInt; 17 | } 18 | } -------------------------------------------------------------------------------- /java/70-climbing-stairs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int climbStairs(int n) { 3 | 4 | int dp[] = new int[n+1]; 5 | dp[n] = 1; 6 | for(int i = n; i>=0; i--){ 7 | if(i+1<=n){ 8 | dp[i] = dp[i+1]; 9 | } 10 | if(i+2<=n){ 11 | dp[i] = dp[i+1] + dp[i+2]; 12 | } 13 | } 14 | 15 | return dp[0]; 16 | } 17 | } -------------------------------------------------------------------------------- /java/704-Binary-Search.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int search(int[] nums, int target) { 4 | int i = 0; 5 | int j = nums.length - 1; 6 | 7 | while (i <= j) { 8 | int mid = (i + j) / 2; 9 | 10 | if (nums[mid] == target) return mid; else if ( 11 | nums[mid] < target 12 | ) i = mid + 1; else j = mid - 1; 13 | } 14 | 15 | return -1; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/746-Min-Cost-Climbing-Stairs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int minCostClimbingStairs(int[] cost) { 4 | int[] res = new int[cost.length + 1]; 5 | res[cost.length] = 0; 6 | res[cost.length - 1] = cost[cost.length - 1]; 7 | 8 | for (int i = cost.length - 2; i >= 0; i--) { 9 | res[i] = 10 | (res[i + 1] < res[i + 2]) 11 | ? res[i + 1] + cost[i] 12 | : res[i + 2] + cost[i]; 13 | } 14 | 15 | return Math.min(res[0], res[1]); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/852. Peak Index in a Mountain Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int peakIndexInMountainArray(int[] arr) { 4 | int left = 0, right = arr.length - 1; 5 | int res = -1; 6 | 7 | while (left <= right) { 8 | int mid = left + (right - left + 1) / 2; 9 | 10 | if (arr[mid - 1] <= arr[mid]) { 11 | left = mid + 1; 12 | res = mid; 13 | } else { 14 | right = mid - 1; 15 | } 16 | } 17 | 18 | return res; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java/876. Middle of the Linked List.java: -------------------------------------------------------------------------------- 1 | //fast and slow pointer 2 | class Solution { 3 | 4 | public ListNode middleNode(ListNode head) { 5 | ListNode slow = head; 6 | ListNode fast = head; 7 | while (fast != null && fast.next != null) { 8 | fast = fast.next.next; 9 | slow = slow.next; 10 | } 11 | return slow; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /java/CheckNumberInString.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class CheckNumberInString { 4 | 5 | public static void main(String[] args) { 6 | String str = "Lorem Ipsum has been the industry's standard dummy text ever since the 1500s."; 7 | Boolean flag = false; 8 | for(int i = 0; i < str.length(); i++) { 9 | flag = Character.isDigit(str.charAt(i)); 10 | if(flag) { 11 | System.out.println(str + "\n ==> contains number"); break; 12 | } 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/LaunchingExternalApps.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | import java.io.IOException; 3 | 4 | public class LaunchingExternalApps { 5 | 6 | public static void main(String[] args) { 7 | Runtime runtime = Runtime.getRuntime(); 8 | try { 9 | runtime.exec("notepad.exe"); 10 | } catch (IOException e) { 11 | e.printStackTrace(); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/NOTES.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajkumarSony/LeetCode-Solutions/a92a72ff0793543c6c4aee95dd624770b14778cc/java/NOTES.md -------------------------------------------------------------------------------- /java/NimGame.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canWinNim(int n) { 3 | if(n%4==0){ 4 | return false; 5 | }else{ 6 | return true; 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /java/inorder.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List inorderTraversal(TreeNode root) { 3 | 4 | 5 | List ans = new ArrayList<>(); 6 | helper(root, ans); 7 | return ans; 8 | 9 | } 10 | 11 | void helper(TreeNode root, List ans){ 12 | 13 | 14 | if(root == null) return; 15 | 16 | helper(root.left, ans); 17 | ans.add(root.val); 18 | helper(root.right, ans); 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /java/isPalindrome.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPalindrome(int x) { 3 | char[] tmp = Integer.toString(x).toCharArray(); 4 | for(int i=0;i preorderTraversal(TreeNode root) { 3 | 4 | List ans = new ArrayList<>(); 5 | helper(root, ans); 6 | return ans; 7 | 8 | 9 | } 10 | 11 | private void helper(TreeNode root, List ans){ 12 | if(root == null) return ; 13 | 14 | ans.add(root.val); 15 | helper(root.left, ans); 16 | helper(root.right, ans); 17 | } 18 | } -------------------------------------------------------------------------------- /javascript/136-Single-Number.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/single-number/ 3 | * Time O(N) | Space O(1) 4 | * @param {number[]} nums 5 | * @return {number} 6 | */ 7 | var singleNumber = function (nums, xor = 0) { 8 | for (num of nums) { 9 | xor ^= num; 10 | } 11 | 12 | return xor; 13 | }; 14 | -------------------------------------------------------------------------------- /javascript/160-Intersection-of-Two-Linked-Lists.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * function ListNode(val) { 4 | * this.val = val; 5 | * this.next = null; 6 | * } 7 | */ 8 | 9 | /** 10 | * @param {ListNode} headA 11 | * @param {ListNode} headB 12 | * @return {ListNode} 13 | */ 14 | var getIntersectionNode = function (headA, headB) { 15 | let a = headA; 16 | let b = headB; 17 | while (a !== b) { 18 | a = a === null ? headB : a.next; 19 | b = b === null ? headA : b.next; 20 | } 21 | 22 | return a; 23 | }; 24 | -------------------------------------------------------------------------------- /javascript/190-Reverse-Bits.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/reverse-bits/ 3 | * Time O(1) | Space O(1) 4 | * @param {number} n - a positive integer 5 | * @return {number} - a positive integer 6 | */ 7 | var reverseBits = function (n, bit = 0) { 8 | for (let i = 0; i < 32; i++) { 9 | bit <<= 1; // Double * 2 10 | bit |= (n & 1); // Flip 11 | n >>= 1; // Reduce * 0.5 12 | } 13 | 14 | return bit >>> 0; 15 | }; 16 | -------------------------------------------------------------------------------- /javascript/268-Missing-Number.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/missing-number/ 3 | * Time O(N) | Space O(1) 4 | * @param {number[]} nums 5 | * @return {number} 6 | */ 7 | var missingNumber = function (nums, missingNumber = nums.length) { 8 | for (let i = 0; i < nums.length; i++) { 9 | const xor = (i ^ nums[i]); 10 | 11 | missingNumber ^= xor; 12 | } 13 | 14 | return missingNumber; 15 | }; 16 | -------------------------------------------------------------------------------- /javascript/338-Counting-Bits.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/counting-bits/ 3 | * Time O(N) | Space (1) 4 | * @param {number} n 5 | * @return {number[]} 6 | */ 7 | var countBits = function (n, dp = [ 0 ]) { 8 | for (let i = 1; i < (n + 1); i++) { 9 | const [ mid, bit ] = [ (i >> 1), (i & 1) ] 10 | const bits = (dp[mid] + bit) 11 | 12 | dp.push(bits); 13 | } 14 | 15 | return dp; 16 | }; 17 | -------------------------------------------------------------------------------- /javascript/371-Sum-of-Two-Integers.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/sum-of-two-integers/ 3 | * Time O(1) | Space O(1) 4 | * @param {number} a 5 | * @param {number} b 6 | * @return {number} 7 | */ 8 | var getSum = function(a, b) { 9 | while (b !== 0) { 10 | const [ xor, carry ] = [ (a ^ b), ((a & b) << 1) ]; 11 | 12 | a = xor; 13 | b = carry; 14 | } 15 | 16 | return a 17 | }; -------------------------------------------------------------------------------- /jewel_and_stone.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numJewelsInStones(self, J, S): 3 | jewels = {} 4 | for i in J: 5 | jewels[i] = 1 6 | number = 0 7 | for i in S: 8 | if i in jewels: 9 | number+=1 10 | return number 11 | ob1 = Solution() 12 | print(ob1.numJewelsInStones("aZc", "catTableZebraPicnic")) -------------------------------------------------------------------------------- /kotlin/1143-Longest-Common-Subsequence.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun longestCommonSubsequence(text1: String, text2: String): Int { 3 | if (text1.isEmpty() || text2.isEmpty()) { 4 | return 0 5 | } 6 | 7 | val M = text1.length 8 | val N = text2.length 9 | 10 | val dp = Array(M + 1){IntArray(N + 1){0}} 11 | 12 | for (i in 1..M) { 13 | for (j in 1..N) { 14 | if (text1[i - 1] == text2[j - 1]) { 15 | dp[i][j] = dp[i - 1][j - 1] + 1 16 | } else { 17 | dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]) 18 | } 19 | } 20 | } 21 | return dp[M][N] 22 | } 23 | } -------------------------------------------------------------------------------- /kotlin/121-Best-Time-to-Buy-and-Sell-Stocks.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun maxProfit(prices: IntArray): Int { 3 | var buy = prices[0] 4 | var maxDiff = 0 5 | for (i in 1 until prices.size) { 6 | buy = buy.coerceAtMost(prices[i]) 7 | maxDiff = maxDiff.coerceAtLeast(prices[i] - buy) 8 | } 9 | return maxDiff 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /kotlin/125-Valid-Palindrome.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun isPalindrome(s: String): Boolean { 3 | val s = s.toLowerCase() 4 | var i = 0 5 | var j = s.length - 1 6 | while (i < j) { 7 | while (!s[i].isLetterOrDigit() && i < j) 8 | i++; 9 | while (!s[j].isLetterOrDigit() && j > i) 10 | j--; 11 | if (s[i++] != s[j--]) return false 12 | } 13 | return true 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /kotlin/136-Single-Number.kt: -------------------------------------------------------------------------------- 1 | package kotlin 2 | 3 | class Solution { 4 | fun singleNumber(nums: IntArray): Int { 5 | var res = 0 6 | 7 | for(n in nums){ 8 | res = res xor n 9 | } 10 | return res 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /kotlin/141-Linked-List-Cycle.kt: -------------------------------------------------------------------------------- 1 | package kotlin 2 | 3 | class Solution { 4 | fun hasCycle(head: ListNode?): Boolean { 5 | if (head == null) return false 6 | var slowPointer = head 7 | var fastPointer = head.next?.next 8 | while (fastPointer != null) { 9 | if (slowPointer === fastPointer) return true 10 | slowPointer = slowPointer?.next 11 | fastPointer = fastPointer.next?.next 12 | } 13 | return false 14 | } 15 | } -------------------------------------------------------------------------------- /kotlin/152-Maximum-Product-Subarray.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun maxProduct(nums: IntArray): Int { 3 | var res = nums[0] 4 | var curMin = 1 5 | var curMax = 1 6 | 7 | for (n in nums) { 8 | val temp = curMax * n 9 | curMax = maxOf(n * curMax, n * curMin, n) 10 | curMin = minOf(temp, n * curMin, n) 11 | res = maxOf(res, curMax) 12 | } 13 | return res 14 | } 15 | } -------------------------------------------------------------------------------- /kotlin/153-Find-Minimum-In-Rotated-Sorted-Array.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun findMin(nums: IntArray): Int { 3 | val n = nums.size 4 | if(n == 1) return nums[0] 5 | var low = 0 6 | var high = n - 1 7 | var min = Int.MIN_VALUE 8 | while(low < high) { 9 | var mid = low + (high - low)/2 10 | if(nums[mid] < nums[high]) { 11 | high = mid 12 | } else { 13 | low = mid + 1 14 | } 15 | min = nums[low] 16 | } 17 | return min 18 | } 19 | } -------------------------------------------------------------------------------- /kotlin/155-Min-Stack.kt: -------------------------------------------------------------------------------- 1 | import kotlin.math.min 2 | 3 | class MinStack() { 4 | private class Node(var `val`: Int, var min: Int, var next: Node?) 5 | 6 | private var head: Node? = null 7 | 8 | fun push(x: Int) { 9 | if(head==null) head = Node(x,x,null) else head = Node(x, min(x,head?.min!!),head) 10 | } 11 | 12 | fun pop() { 13 | head = head?.next 14 | 15 | } 16 | 17 | fun top(): Int? { 18 | return head?.`val` 19 | 20 | } 21 | 22 | fun getMin(): Int? { 23 | return head?.min 24 | 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /kotlin/167-Two-Sum-2.kt: -------------------------------------------------------------------------------- 1 | package kotlin 2 | 3 | fun twoSum(numbers: IntArray, target: Int): IntArray { 4 | var l = 0 5 | var r = numbers.size - 1 6 | 7 | while(l < r) { 8 | val sum = numbers[l] + numbers[r] 9 | if(sum < target){ 10 | l++ 11 | } else if(sum > target){ 12 | r-- 13 | } else { 14 | return intArrayOf(l+1, r+1) 15 | } 16 | } 17 | 18 | return intArrayOf(-1, -1) 19 | } -------------------------------------------------------------------------------- /kotlin/190-Reverse-Bits.kt: -------------------------------------------------------------------------------- 1 | package kotlin 2 | 3 | 4 | class Solution { 5 | // you need treat n as an unsigned value 6 | fun reverseBits(n: Int): Int { 7 | var n = n 8 | if(n == 0) return 0 9 | var result = 0 10 | for( i in 0 .. 31){ 11 | result = result shl 1 12 | if(n and 1 == 1) result++ 13 | n = n shr 1 14 | } 15 | 16 | return result 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /kotlin/191-Number-Of-1-Bits.kt: -------------------------------------------------------------------------------- 1 | package kotlin 2 | 3 | class Solution { 4 | // you need treat n as an unsigned value 5 | fun hammingWeight(n:Int):Int { 6 | 7 | var n = n 8 | var count = 0 9 | for(i in 0..31){ 10 | if( n and 1 == 1) count++ 11 | n = n shr 1 12 | } 13 | 14 | return count 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /kotlin/198-House-Robber.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun rob(nums: IntArray): Int { 3 | var rob = 0 4 | var notRob = 0 5 | nums.forEach { 6 | val currRob = notRob + it 7 | notRob = maxOf(notRob, rob) 8 | rob = currRob 9 | } 10 | 11 | return maxOf(rob, notRob) 12 | } 13 | } -------------------------------------------------------------------------------- /kotlin/20-Valid-Parentheses.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun isValid(s: String): Boolean { 3 | if (s.length % 2 == 1) return false 4 | 5 | val map = hashMapOf('(' to ')', '[' to ']', '{' to '}') 6 | val stack = Stack() 7 | 8 | for (c in s) { 9 | if (map.containsKey(c)) 10 | stack.push(c) 11 | else if (stack.isEmpty() || map[stack.pop()] != c) 12 | return false 13 | } 14 | return stack.isEmpty() 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /kotlin/215-Kth-Largest-Element-In-Array.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun findKthLargest(nums: IntArray, k: Int): Int { 3 | val heap = PriorityQueue() 4 | 5 | for (num in nums) { 6 | heap.add(num) 7 | 8 | if (heap.size > k) 9 | heap.poll() 10 | } 11 | 12 | return heap.peek() 13 | } 14 | } -------------------------------------------------------------------------------- /kotlin/217-Contains-Duplicate.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun containsDuplicate(nums: IntArray): Boolean { 3 | val hs = HashSet() 4 | for (e in nums) 5 | if (!hs.add(e)) return true 6 | return false 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /kotlin/226-Invert-Binary-Tree.kt: -------------------------------------------------------------------------------- 1 | /** 2 | * Example: 3 | * var ti = TreeNode(5) 4 | * var v = ti.`val` 5 | * Definition for a binary tree node. 6 | * class TreeNode(var `val`: Int) { 7 | * var left: TreeNode? = null 8 | * var right: TreeNode? = null 9 | * } 10 | */ 11 | class Solution { 12 | fun invertTree(root: TreeNode?): TreeNode? { 13 | if (root == null) 14 | return root 15 | 16 | val left = invertTree(root.left) 17 | root.left = invertTree(root.right) 18 | root.right = left 19 | 20 | return root 21 | } 22 | } -------------------------------------------------------------------------------- /kotlin/238-Product-Of-Array-Except-Self.kt: -------------------------------------------------------------------------------- 1 | package kotlin 2 | 3 | 4 | fun main() { 5 | val nums = intArrayOf(1, 2, 3, 4) 6 | //o.p : 24, 12,8,6 7 | } 8 | 9 | fun productExceptSelf(nums: IntArray): IntArray { 10 | val res = IntArray(nums.size) 11 | 12 | var prefix = 1 13 | 14 | for (i in 0 until nums.size) { 15 | res[i] = prefix 16 | prefix *= nums[i] 17 | } 18 | 19 | var postfix = 1 20 | for (i in nums.size - 1 downTo 0) { 21 | res[i] *= postfix 22 | postfix *= nums[i] 23 | } 24 | 25 | return res 26 | } -------------------------------------------------------------------------------- /kotlin/242-Valid-Anagram.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun isAnagram(s: String, t: String): Boolean { 3 | if (s.length != t.length) return false 4 | val arr = Array(26) {0} 5 | for (i in s.indices) { 6 | arr[s[i] - 'a']++ 7 | arr[t[i] - 'a']-- 8 | } 9 | return arr.all{it == 0} 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /kotlin/268-Missing-Number.kt: -------------------------------------------------------------------------------- 1 | package kotlin 2 | 3 | class Solution { 4 | fun missingNumber(nums: IntArray): Int { 5 | var missing = nums.size 6 | for(i in nums.indices){ 7 | missing = missing xor i xor nums[i] 8 | } 9 | 10 | return missing 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /kotlin/3-Longest-Substring-Without-Repeating-Characters.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun lengthOfLongestSubstring(s: String): Int { 3 | val hs = HashSet() 4 | var i = 0 5 | var j = 0 6 | var maxLength = 0 7 | while (j < s.length) { 8 | if (hs.contains(s[j])) { 9 | hs.remove(s[i++]) 10 | } else { 11 | hs.add(s[j++]) 12 | maxLength = maxLength.coerceAtLeast(hs.size) 13 | } 14 | } 15 | return maxLength 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /kotlin/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun maxProfit(prices: IntArray): Int { 3 | var sold = 0 4 | var hold = Int.MIN_VALUE 5 | var rest = 0 6 | 7 | for (i in 0..prices.size-1) { 8 | val prevSold = sold 9 | sold = hold + prices[i] 10 | hold = maxOf(hold, rest - prices[i]) 11 | rest = maxOf(rest, prevSold) 12 | } 13 | return maxOf(sold, rest) 14 | } 15 | } -------------------------------------------------------------------------------- /kotlin/322-Coin-Change.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun coinChange(coins: IntArray, amount: Int): Int { 3 | val dp = IntArray(amount+1){amount+1} 4 | dp[0] = 0 5 | for(i in 0 .. amount){ 6 | for (j in 0 until coins.size){ 7 | if(coins[j]<=i){ 8 | dp[i] = minOf(dp[i], dp[i-coins[j]]+1) 9 | } 10 | } 11 | } 12 | return if(dp[amount]>amount) -1 else dp[amount] 13 | } 14 | } -------------------------------------------------------------------------------- /kotlin/338-Counting-Bits.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun countBits(n: Int): IntArray { 3 | var dp = IntArray(n + 1) 4 | var offset = 1 5 | 6 | for (i in 1..n) { 7 | if (offset * 2 == i) { 8 | offset = i 9 | } 10 | dp[i] = 1 + dp[i - offset] 11 | } 12 | return dp 13 | } 14 | } -------------------------------------------------------------------------------- /kotlin/371-Sum-Of-Two-Integers.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun getSum(a: Int, b: Int): Int { 3 | var a1 = a 4 | var b1 = b 5 | var carry = a1.and(b1) 6 | while (carry != 0) { 7 | b1 = a1.xor(b1) 8 | a1 = carry.shl(1) 9 | carry = a1.and(b1) 10 | } 11 | return a1.xor(b1) 12 | } 13 | } -------------------------------------------------------------------------------- /kotlin/45-Jump-Game-II.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun jump(nums: IntArray): Int { 3 | var left = 0 4 | var right = 0 5 | var res = 0 6 | 7 | while (right < nums.size - 1) { 8 | var maxJump = 0 9 | for (i in left..right) { 10 | maxJump = maxOf(maxJump, i + nums[i]) 11 | } 12 | left = right + 1 13 | right = maxJump 14 | res += 1 15 | } 16 | return res 17 | } 18 | } -------------------------------------------------------------------------------- /kotlin/53-Maximum-Subarray.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun maxSubArray(nums: IntArray): Int { 3 | var sum = nums[0] 4 | var currsum = 0 5 | for (num in nums) { 6 | currsum = maxOf(currsum + num, num) 7 | sum = maxOf(currsum, sum) 8 | } 9 | return sum 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /kotlin/55-Jump-Game.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun canJump(nums: IntArray): Boolean { 3 | var goal = nums.size - 1 4 | 5 | for (i in nums.size - 2 downTo 0) { 6 | if (i + nums[i] >= goal) { 7 | goal = i 8 | } 9 | } 10 | return goal == 0 11 | } 12 | } -------------------------------------------------------------------------------- /kotlin/56-Merge-Intervals.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun merge(intervals: Array): Array { 3 | intervals.sortBy{ it.first() } 4 | val list = LinkedList() 5 | 6 | for (interval in intervals) { 7 | if (list.size == 0 || list.last[1] < interval[0]) { 8 | list.add(interval) 9 | } else { 10 | list.last[1] = Math.max(list.last[1], interval[1]) 11 | } 12 | } 13 | 14 | return list.toTypedArray() 15 | } 16 | } -------------------------------------------------------------------------------- /kotlin/62-Unique-Paths.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun uniquePaths(m: Int, n: Int): Int { 3 | val dp = Array(m + 1) { IntArray(n + 1) { 0 } } 4 | val indexM = m - 1 5 | val indexN = n - 1 6 | for (i in indexM downTo 0) { 7 | for (j in indexN downTo 0) { 8 | if (i == indexM && j == indexN) { 9 | dp[i][j] = 1 10 | } else { 11 | dp[i][j] = dp[i + 1][j] + dp[i][j + 1] 12 | } 13 | } 14 | } 15 | return dp[0][0] 16 | } 17 | } -------------------------------------------------------------------------------- /kotlin/66-Plus-One.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun plusOne(digits: IntArray): IntArray { 3 | for (i in digits.size-1 downTo 0) { 4 | digits[i] += 1 5 | 6 | if (digits[i] <= 9) 7 | return digits 8 | 9 | digits[i] = 0 10 | } 11 | 12 | return IntArray(digits.size+1).also{ it[0] = 1 } 13 | } 14 | } -------------------------------------------------------------------------------- /kotlin/70-Climbing-Stairs.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun climbStairs(n: Int): Int { 3 | if (n <= 3) { 4 | return n 5 | } 6 | var n1 = 2 7 | var n2 = 3 8 | 9 | for (i in 4..n) { 10 | val temp = n1 + n2 11 | n1 = n2 12 | n2 = temp 13 | } 14 | return n2 15 | } 16 | } -------------------------------------------------------------------------------- /kotlin/704-Binary-Search.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun search(nums: IntArray, target: Int): Int { 3 | return searchAux(nums, target, 0, nums.size - 1) 4 | } 5 | 6 | private fun searchAux(nums: IntArray, target: Int, begin: Int, end: Int): Int { 7 | if (begin > end) return -1 8 | 9 | val mid: Int = (begin + end) / 2 10 | 11 | return if (nums[mid] == target) mid 12 | else if (nums[mid] > target) searchAux(nums, target, begin, mid - 1) 13 | else searchAux(nums, target, mid + 1, end) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /kotlin/746-Min-Cost-Climbing-Stairs.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun minCostClimbingStairs(cost: IntArray): Int { 3 | for (i in cost.size - 3 downTo 0) { 4 | cost[i] += minOf(cost[i + 1], cost[i + 2]) 5 | } 6 | return minOf(cost[0], cost[1]) 7 | } 8 | } -------------------------------------------------------------------------------- /kotlin/78-Subsets.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun subsets(nums: IntArray): List> { 3 | val res = mutableListOf>() 4 | subsets(nums, 0, mutableListOf(), res) 5 | return res 6 | } 7 | 8 | fun subsets(nums: IntArray, idx: Int, list: MutableList, res: MutableList>) { 9 | res.add(ArrayList(list)) 10 | 11 | for (i in idx..nums.size-1) { 12 | list.add(nums[i]) 13 | subsets(nums, i+1, list, res) 14 | list.removeAt(list.size-1) 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /kotlin/91-Decode-Ways.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun numDecodings(s: String): Int { 3 | val n = s.length 4 | val dp = IntArray(n+1) 5 | dp[0] = 1 6 | dp[1] = if (s[0] == '0') 0 else 1 7 | 8 | for (i in 2..n) { 9 | val curr = s[i-1] - '0' 10 | val prev = s[i-2] - '0' 11 | val num = 10*prev + curr 12 | 13 | if (curr > 0) 14 | dp[i] += dp[i-1] 15 | 16 | if (num >= 10 && num <= 26) 17 | dp[i] += dp[i-2] 18 | } 19 | 20 | return dp[n] 21 | } 22 | } -------------------------------------------------------------------------------- /kotlin/973-K-Closest-Points-To-Origin.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun kClosest(points: Array, k: Int): Array { 3 | val sorted = points.sortedBy{ it[0]*it[0] + it[1]*it[1]} 4 | val list = arrayListOf() 5 | 6 | for (i in 0..k-1) { 7 | list.add(sorted[i]) 8 | } 9 | 10 | return list.toTypedArray() 11 | } 12 | } -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajkumarSony/LeetCode-Solutions/a92a72ff0793543c6c4aee95dd624770b14778cc/logo.png -------------------------------------------------------------------------------- /python/1-Two-Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | prevMap = {} # val -> index 4 | 5 | for i, n in enumerate(nums): 6 | diff = target - n 7 | if diff in prevMap: 8 | return [prevMap[diff], i] 9 | prevMap[n] = i 10 | -------------------------------------------------------------------------------- /python/100-Same-Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | 9 | class Solution: 10 | def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: 11 | if not p and not q: 12 | return True 13 | if p and q and p.val == q.val: 14 | return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) 15 | else: 16 | return False 17 | -------------------------------------------------------------------------------- /python/1046-Last-Stone-Weight.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lastStoneWeight(self, stones: List[int]) -> int: 3 | stones = [-s for s in stones] 4 | heapq.heapify(stones) 5 | 6 | while len(stones) > 1: 7 | first = heapq.heappop(stones) 8 | second = heapq.heappop(stones) 9 | if second > first: 10 | heapq.heappush(stones, first - second) 11 | 12 | stones.append(0) 13 | return abs(stones[0]) 14 | -------------------------------------------------------------------------------- /python/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: 3 | if not preorder or not inorder: 4 | return None 5 | 6 | root = TreeNode(preorder[0]) 7 | mid = inorder.index(preorder[0]) 8 | root.left = self.buildTree(preorder[1 : mid + 1], inorder[:mid]) 9 | root.right = self.buildTree(preorder[mid + 1 :], inorder[mid + 1 :]) 10 | return root 11 | -------------------------------------------------------------------------------- /python/11-Container-With-Most-Water.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxArea(self, height: List[int]) -> int: 3 | l, r = 0, len(height) - 1 4 | res = 0 5 | 6 | while l < r: 7 | res = max(res, min(height[l], height[r]) * (r - l)) 8 | if height[l] < height[r]: 9 | l += 1 10 | elif height[r] <= height[l]: 11 | r -= 1 12 | return res 13 | -------------------------------------------------------------------------------- /python/1137-N-th-Tribonacci-Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | Memo = {} 3 | 4 | def tribonacci(self, n: int): 5 | if n in self.Memo: 6 | return self.Memo[n] 7 | if n == 0: 8 | return 0 9 | if n == 1: 10 | return 1 11 | if n == 2: 12 | return 1 13 | self.Memo[n] = ( 14 | self.tribonacci(n - 1) + self.tribonacci(n - 2) + self.tribonacci(n - 3) 15 | ) 16 | return self.Memo[n] 17 | -------------------------------------------------------------------------------- /python/1143-Longest-Common-Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonSubsequence(self, text1: str, text2: str) -> int: 3 | dp = [[0 for j in range(len(text2) + 1)] for i in range(len(text1) + 1)] 4 | 5 | for i in range(len(text1) - 1, -1, -1): 6 | for j in range(len(text2) - 1, -1, -1): 7 | if text1[i] == text2[j]: 8 | dp[i][j] = 1 + dp[i + 1][j + 1] 9 | else: 10 | dp[i][j] = max(dp[i][j + 1], dp[i + 1][j]) 11 | 12 | return dp[0][0] 13 | -------------------------------------------------------------------------------- /python/118-Pascals-Triangle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generate(self, numRows: int) -> List[List[int]]: 3 | triangle = [] 4 | for row_num in range(numRows): 5 | row = [None for _ in range(row_num + 1)] 6 | row[0], row[-1] = 1, 1 7 | for j in range(1, row_num): 8 | row[j] = triangle[row_num - 1][j-1] + triangle[row_num - 1][j] 9 | triangle.append(row) 10 | return triangle 11 | -------------------------------------------------------------------------------- /python/119-Pascal-Triangle-II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | Memo = {} 3 | 4 | def getRow(self, rowIndex: int) -> List[int]: 5 | if rowIndex in self.Memo: 6 | return self.Memo[rowIndex] 7 | if rowIndex == 0: 8 | return [1] 9 | ListPrec = self.getRow(rowIndex - 1) 10 | Result = [1] 11 | for i in range(0, len(ListPrec) - 1): 12 | Result.append(ListPrec[i] + ListPrec[i + 1]) 13 | Result.append(1) 14 | self.Memo[rowIndex] = Result 15 | return Result 16 | -------------------------------------------------------------------------------- /python/1209-Remove-All-Adjacent-Duplicates-in-String-II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, s: str, k: int) -> str: 3 | stack = [] # [char, count] 4 | 5 | for c in s: 6 | if stack and stack[-1][0] == c: 7 | stack[-1][1] += 1 8 | else: 9 | stack.append([c, 1]) 10 | 11 | if stack[-1][1] == k: 12 | stack.pop() 13 | 14 | res = "" 15 | for char, count in stack: 16 | res += char * count 17 | 18 | return res 19 | -------------------------------------------------------------------------------- /python/121-Best-Time-To-Buy-and-Sell-Stock.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | res = 0 4 | 5 | l = 0 6 | for r in range(1, len(prices)): 7 | if prices[r] < prices[l]: 8 | l = r 9 | res = max(res, prices[r] - prices[l]) 10 | return res 11 | -------------------------------------------------------------------------------- /python/128-Longest-consecutive-sequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestConsecutive(self, nums: List[int]) -> int: 3 | numSet = set(nums) 4 | longest = 0 5 | 6 | for n in nums: 7 | # check if its the start of a sequence 8 | if (n - 1) not in numSet: 9 | length = 1 10 | while (n + length) in numSet: 11 | length += 1 12 | longest = max(length, longest) 13 | return longest 14 | -------------------------------------------------------------------------------- /python/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def replaceElements(self, arr: List[int]) -> List[int]: 3 | rightMax = -1 4 | for i in range(len(arr) -1, -1, -1): 5 | newMax = max(rightMax, arr[i]) 6 | arr[i] = rightMax 7 | rightMax = newMax 8 | return arr 9 | -------------------------------------------------------------------------------- /python/13-Roman-To-Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def romanToInt(self, s: str) -> int: 3 | roman = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} 4 | res = 0 5 | for i in range(len(s)): 6 | if i + 1 < len(s) and roman[s[i]] < roman[s[i + 1]]: 7 | res -= roman[s[i]] 8 | else: 9 | res += roman[s[i]] 10 | return res 11 | -------------------------------------------------------------------------------- /python/133-Clone-Graph.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def cloneGraph(self, node: "Node") -> "Node": 3 | oldToNew = {} 4 | 5 | def dfs(node): 6 | if node in oldToNew: 7 | return oldToNew[node] 8 | 9 | copy = Node(node.val) 10 | oldToNew[node] = copy 11 | for nei in node.neighbors: 12 | copy.neighbors.append(dfs(nei)) 13 | return copy 14 | 15 | return dfs(node) if node else None 16 | -------------------------------------------------------------------------------- /python/134-Gas-Station.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: 3 | start, end = len(gas) - 1, 0 4 | total = gas[start] - cost[start] 5 | 6 | while start >= end: 7 | while total < 0 and start >= end: 8 | start -= 1 9 | total += gas[start] - cost[start] 10 | if start == end: 11 | return start 12 | total += gas[end] - cost[end] 13 | end += 1 14 | return -1 15 | -------------------------------------------------------------------------------- /python/136-Single-Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumber(self, nums: List[int]) -> int: 3 | res = 0 4 | for n in nums: 5 | res = n ^ res 6 | return res 7 | -------------------------------------------------------------------------------- /python/139-Word-Break.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wordBreak(self, s: str, wordDict: List[str]) -> bool: 3 | 4 | dp = [False] * (len(s) + 1) 5 | dp[len(s)] = True 6 | 7 | for i in range(len(s) - 1, -1, -1): 8 | for w in wordDict: 9 | if (i + len(w)) <= len(s) and s[i : i + len(w)] == w: 10 | dp[i] = dp[i + len(w)] 11 | if dp[i]: 12 | break 13 | 14 | return dp[0] 15 | -------------------------------------------------------------------------------- /python/14-Longest-Common-Prefix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonPrefix(self, strs: List[str]) -> str: 3 | res = "" 4 | for i in range(len(strs[0])): 5 | for s in strs: 6 | if i == len(s) or s[i] != strs[0][i]: 7 | return res 8 | res += strs[0][i] 9 | return res 10 | -------------------------------------------------------------------------------- /python/141-Linked-List-Cycle.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | 8 | class Solution: 9 | def hasCycle(self, head: ListNode) -> bool: 10 | slow, fast = head, head 11 | 12 | while fast and fast.next: 13 | slow = slow.next 14 | fast = fast.next.next 15 | if slow == fast: 16 | return True 17 | return False 18 | -------------------------------------------------------------------------------- /python/152-Maximum-Product-Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProduct(self, nums: List[int]) -> int: 3 | # O(n)/O(1) : Time/Memory 4 | res = nums[0] 5 | curMin, curMax = 1, 1 6 | 7 | for n in nums: 8 | 9 | tmp = curMax * n 10 | curMax = max(n * curMax, n * curMin, n) 11 | curMin = min(tmp, n * curMin, n) 12 | res = max(res, curMax) 13 | return res 14 | -------------------------------------------------------------------------------- /python/153-Find-Minimum-in-Rotated-Sorted-Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMin(self, nums: List[int]) -> int: 3 | res = nums[0] 4 | l, r = 0, len(nums) - 1 5 | 6 | while l <= r: 7 | if nums[l] < nums[r]: 8 | res = min(res, nums[l]) 9 | break 10 | m = (l + r) // 2 11 | res = min(res, nums[m]) 12 | if nums[m] >= nums[l]: 13 | l = m + 1 14 | else: 15 | r = m - 1 16 | return res 17 | -------------------------------------------------------------------------------- /python/155-Min-Stack.py: -------------------------------------------------------------------------------- 1 | class MinStack: 2 | def __init__(self): 3 | self.stack = [] 4 | self.minStack = [] 5 | 6 | def push(self, val: int) -> None: 7 | self.stack.append(val) 8 | val = min(val, self.minStack[-1] if self.minStack else val) 9 | self.minStack.append(val) 10 | 11 | def pop(self) -> None: 12 | self.stack.pop() 13 | self.minStack.pop() 14 | 15 | def top(self) -> int: 16 | return self.stack[-1] 17 | 18 | def getMin(self) -> int: 19 | return self.minStack[-1] 20 | -------------------------------------------------------------------------------- /python/160-Intersection-of-Two-Linked-Lists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | 8 | class Solution: 9 | def getIntersectionNode( 10 | self, headA: ListNode, headB: ListNode 11 | ) -> Optional[ListNode]: 12 | l1, l2 = headA, headB 13 | while l1 != l2: 14 | l1 = l1.next if l1 else headB 15 | l2 = l2.next if l2 else headA 16 | return l1 17 | -------------------------------------------------------------------------------- /python/167-Two-Sum-II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, numbers: List[int], target: int) -> List[int]: 3 | l, r = 0, len(numbers) - 1 4 | 5 | while l < r: 6 | curSum = numbers[l] + numbers[r] 7 | 8 | if curSum > target: 9 | r -= 1 10 | elif curSum < target: 11 | l += 1 12 | else: 13 | return [l + 1, r + 1] 14 | -------------------------------------------------------------------------------- /python/1899-Merge-Triplets-to-Form-Target-Triplet.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool: 3 | good = set() 4 | 5 | for t in triplets: 6 | if t[0] > target[0] or t[1] > target[1] or t[2] > target[2]: 7 | continue 8 | for i, v in enumerate(t): 9 | if v == target[i]: 10 | good.add(i) 11 | return len(good) == 3 12 | -------------------------------------------------------------------------------- /python/19-Remove-Nth-node-from-end-of-List.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: 3 | dummy = ListNode(0, head) 4 | left = dummy 5 | right = head 6 | 7 | while n > 0: 8 | right = right.next 9 | n -= 1 10 | 11 | while right: 12 | left = left.next 13 | right = right.next 14 | 15 | # delete 16 | left.next = left.next.next 17 | return dummy.next 18 | -------------------------------------------------------------------------------- /python/190-Reverse-Bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseBits(self, n: int) -> int: 3 | res = 0 4 | for i in range(32): 5 | bit = (n >> i) & 1 6 | res += (bit << (31 - i)) 7 | return res 8 | -------------------------------------------------------------------------------- /python/191-Number-of-1-Bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hammingWeight(self, n: int) -> int: 3 | res = 0 4 | while n: 5 | n &= n - 1 6 | res += 1 7 | return res 8 | -------------------------------------------------------------------------------- /python/198-House-Robber.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, nums: List[int]) -> int: 3 | rob1, rob2 = 0, 0 4 | 5 | for n in nums: 6 | temp = max(n + rob1, rob2) 7 | rob1 = rob2 8 | rob2 = temp 9 | return rob2 10 | -------------------------------------------------------------------------------- /python/1985-Find-The-Kth-Largest-Integer-In-The-Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthLargestNumber(self, nums: List[str], k: int) -> str: 3 | maxHeap = [-int(n) for n in nums] 4 | heapq.heapify(maxHeap) 5 | while k>1: 6 | heapq.heappop(maxHeap) 7 | k-=1 8 | return str(-maxHeap[0]) 9 | -------------------------------------------------------------------------------- /python/20-Valid-Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValid(self, s: str) -> bool: 3 | Map = {")": "(", "]": "[", "}": "{"} 4 | stack = [] 5 | 6 | for c in s: 7 | if c not in Map: 8 | stack.append(c) 9 | continue 10 | if not stack or stack[-1] != Map[c]: 11 | return False 12 | stack.pop() 13 | 14 | return not stack 15 | -------------------------------------------------------------------------------- /python/202-Happy-Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isHappy(self, n: int) -> bool: 3 | slow, fast = n, self.sumSquareDigits(n) 4 | 5 | while slow != fast: 6 | fast = self.sumSquareDigits(fast) 7 | fast = self.sumSquareDigits(fast) 8 | slow = self.sumSquareDigits(slow) 9 | 10 | return True if fast == 1 else False 11 | 12 | def sumSquareDigits(self, n): 13 | output = 0 14 | while n: 15 | output += (n % 10) ** 2 16 | n = n // 10 17 | return output 18 | -------------------------------------------------------------------------------- /python/206-Reverse-Linked-List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | 8 | class Solution: 9 | def reverseList(self, head: ListNode) -> ListNode: 10 | prev, curr = None, head 11 | 12 | while curr: 13 | temp = curr.next 14 | curr.next = prev 15 | prev = curr 16 | curr = temp 17 | return prev 18 | -------------------------------------------------------------------------------- /python/213-House-Robber-II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, nums: List[int]) -> int: 3 | return max(nums[0], self.helper(nums[1:]), self.helper(nums[:-1])) 4 | 5 | def helper(self, nums): 6 | rob1, rob2 = 0, 0 7 | 8 | for n in nums: 9 | newRob = max(rob1 + n, rob2) 10 | rob1 = rob2 11 | rob2 = newRob 12 | return rob2 13 | -------------------------------------------------------------------------------- /python/217-Contains-Duplicate.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsDuplicate(self, nums: List[int]) -> bool: 3 | hashset = set() 4 | 5 | for n in nums: 6 | if n in hashset: 7 | return True 8 | hashset.add(n) 9 | return False 10 | -------------------------------------------------------------------------------- /python/238-Product-of-array-except-self.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def productExceptSelf(self, nums: List[int]) -> List[int]: 3 | res = [1] * (len(nums)) 4 | 5 | prefix = 1 6 | for i in range(len(nums)): 7 | res[i] = prefix 8 | prefix *= nums[i] 9 | postfix = 1 10 | for i in range(len(nums) - 1, -1, -1): 11 | res[i] *= postfix 12 | postfix *= nums[i] 13 | return res 14 | -------------------------------------------------------------------------------- /python/242-Valid-Anagrams.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isAnagram(self, s: str, t: str) -> bool: 3 | if len(s) != len(t): 4 | return False 5 | 6 | countS, countT = {}, {} 7 | 8 | for i in range(len(s)): 9 | countS[s[i]] = 1 + countS.get(s[i], 0) 10 | countT[t[i]] = 1 + countT.get(t[i], 0) 11 | return countS == countT 12 | -------------------------------------------------------------------------------- /python/252-Meeting-Rooms.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param intervals: an array of meeting time intervals 4 | @return: if a person could attend all meetings 5 | """ 6 | 7 | def canAttendMeetings(self, intervals): 8 | intervals.sort(key=lambda i: i[0]) 9 | 10 | for i in range(1, len(intervals)): 11 | i1 = intervals[i - 1] 12 | i2 = intervals[i] 13 | 14 | if i1[1] > i2[0]: 15 | return False 16 | return True 17 | -------------------------------------------------------------------------------- /python/26-Remove-Duplicates-from-Sorted Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeDuplicates(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | k = 0 8 | i = 0 9 | while i < len(nums): 10 | val = nums[i] 11 | while i + 1 < len(nums) and nums[i + 1] == val: 12 | nums.remove(val) 13 | k += 1 14 | i += 1 15 | return len(nums) 16 | -------------------------------------------------------------------------------- /python/268-Missing-Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def missingNumber(self, nums: List[int]) -> int: 3 | res = len(nums) 4 | 5 | for i in range(len(nums)): 6 | res += i - nums[i] 7 | return res 8 | -------------------------------------------------------------------------------- /python/27-Remove-Element.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeElement(self, nums, val): 3 | """ 4 | :type nums: List[int] 5 | :type val: int 6 | :rtype: int 7 | """ 8 | for i in range(nums.count(val)): # loop how many val is in the list 9 | nums.remove(val) # remove each val one by one 10 | return len(nums) # return len of nums 11 | -------------------------------------------------------------------------------- /python/287-Find-The-Duplicate-Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDuplicate(self, nums: List[int]) -> int: 3 | slow, fast = 0, 0 4 | while True: 5 | slow = nums[slow] 6 | fast = nums[nums[fast]] 7 | if slow == fast: 8 | break 9 | 10 | slow2 = 0 11 | while True: 12 | slow = nums[slow] 13 | slow2 = nums[slow2] 14 | if slow == slow2: 15 | return slow 16 | -------------------------------------------------------------------------------- /python/3-Longest-Substring-Without-Repeating-Characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstring(self, s: str) -> int: 3 | sub = set() 4 | j, l, m = 0, 0, 0 5 | 6 | while j < len(s): 7 | while s[j] in sub: 8 | sub.remove(s[l]) 9 | l += 1 10 | sub.add(s[j]) 11 | m = max(m, j - l + 1) 12 | j += 1 13 | return m 14 | 15 | -------------------------------------------------------------------------------- /python/300-Longest-Increasing-Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLIS(self, nums: List[int]) -> int: 3 | LIS = [1] * len(nums) 4 | 5 | for i in range(len(nums) - 1, -1, -1): 6 | for j in range(i + 1, len(nums)): 7 | if nums[i] < nums[j]: 8 | LIS[i] = max(LIS[i], 1 + LIS[j]) 9 | return max(LIS) 10 | -------------------------------------------------------------------------------- /python/322-Coin-Change.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def coinChange(self, coins: List[int], amount: int) -> int: 3 | dp = [amount + 1] * (amount + 1) 4 | dp[0] = 0 5 | 6 | for a in range(1, amount + 1): 7 | for c in coins: 8 | if a - c >= 0: 9 | dp[a] = min(dp[a], 1 + dp[a - c]) 10 | return dp[amount] if dp[amount] != amount + 1 else -1 11 | -------------------------------------------------------------------------------- /python/338-Counting-Bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countBits(self, n: int) -> List[int]: 3 | dp = [0] * (n + 1) 4 | offset = 1 5 | 6 | for i in range(1, n + 1): 7 | if offset * 2 == i: 8 | offset = i 9 | dp[i] = 1 + dp[i - offset] 10 | return dp 11 | -------------------------------------------------------------------------------- /python/347-Top-k-frequent-elements.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 3 | count = {} 4 | freq = [[] for i in range(len(nums) + 1)] 5 | 6 | for n in nums: 7 | count[n] = 1 + count.get(n, 0) 8 | for n, c in count.items(): 9 | freq[c].append(n) 10 | 11 | res = [] 12 | for i in range(len(freq) - 1, 0, -1): 13 | for n in freq[i]: 14 | res.append(n) 15 | if len(res) == k: 16 | return res 17 | 18 | # O(n) 19 | -------------------------------------------------------------------------------- /python/35-Search-Insert-Position.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchInsert(self, nums: List[int], target: int) -> int: 3 | # O(log n) and O(1) 4 | 5 | 6 | low, high = 0, len(nums) 7 | while low nums[mid]: 10 | low = mid + 1 11 | else: 12 | high = mid 13 | return low 14 | -------------------------------------------------------------------------------- /python/392-Is-Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isSubsequence(self, s: str, t: str) -> bool: 3 | i, j = 0, 0 4 | while i < len(s) and j < len(t): 5 | if s[i] == t[j]: 6 | i += 1 7 | j += 1 8 | return i == len(s) 9 | -------------------------------------------------------------------------------- /python/416-Partition-Equal-Subset-Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canPartition(self, nums: List[int]) -> bool: 3 | if sum(nums) % 2: 4 | return False 5 | 6 | dp = set() 7 | dp.add(0) 8 | target = sum(nums) // 2 9 | 10 | for i in range(len(nums) - 1, -1, -1): 11 | nextDP = set() 12 | for t in dp: 13 | if (t + nums[i]) == target: 14 | return True 15 | nextDP.add(t + nums[i]) 16 | nextDP.add(t) 17 | dp = nextDP 18 | return False 19 | -------------------------------------------------------------------------------- /python/424-Longest-Repeating-Character-Replacement.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def characterReplacement(self, s: str, k: int) -> int: 3 | count = {} 4 | res = 0 5 | 6 | l = 0 7 | maxf = 0 8 | for r in range(len(s)): 9 | count[s[r]] = 1 + count.get(s[r], 0) 10 | maxf = max(maxf, count[s[r]]) 11 | 12 | if (r - l + 1) - maxf > k: 13 | count[s[l]] -= 1 14 | l += 1 15 | 16 | res = max(res, r - l + 1) 17 | return res 18 | -------------------------------------------------------------------------------- /python/435-Non-Overlapping-Intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: 3 | intervals.sort() 4 | res = 0 5 | prevEnd = intervals[0][1] 6 | for start, end in intervals[1:]: 7 | if start >= prevEnd: 8 | prevEnd = end 9 | else: 10 | res += 1 11 | prevEnd = min(end, prevEnd) 12 | return res 13 | -------------------------------------------------------------------------------- /python/441-Arranging-Coin.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arrangeCoins(self, n: int) -> int: 3 | l, r = 1, n 4 | res = 0 5 | while l <=r: 6 | mid = (l+r)//2 7 | coins = (mid /2) * (mid+1) 8 | if coins > n: 9 | r = mid - 1 10 | else: 11 | l = mid + 1 12 | res = max(mid, res) 13 | return res 14 | -------------------------------------------------------------------------------- /python/448-Find-all-Numbers-Disappeared-in-an-Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDisappearedNumbers(self, nums: List[int]) -> List[int]: 3 | for n in nums: 4 | i = abs(n) - 1 5 | nums[i] = -1 * abs(nums[i]) 6 | 7 | res = [] 8 | for i, n in enumerate(nums): 9 | if n > 0: 10 | res.append(i + 1) 11 | return res 12 | -------------------------------------------------------------------------------- /python/45-Jump-Game-II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jump(self, nums: List[int]) -> int: 3 | l, r = 0, 0 4 | res = 0 5 | while r < (len(nums) - 1): 6 | maxJump = 0 7 | for i in range(l, r + 1): 8 | maxJump = max(maxJump, i + nums[i]) 9 | l = r + 1 10 | r = maxJump 11 | res += 1 12 | return res 13 | -------------------------------------------------------------------------------- /python/46-Permutations.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def permute(self, nums: List[int]) -> List[List[int]]: 3 | res = [] 4 | 5 | # base case 6 | if len(nums) == 1: 7 | return [nums[:]] # nums[:] is a deep copy 8 | 9 | for i in range(len(nums)): 10 | n = nums.pop(0) 11 | perms = self.permute(nums) 12 | 13 | for perm in perms: 14 | perm.append(n) 15 | res.extend(perms) 16 | nums.append(n) 17 | return res 18 | -------------------------------------------------------------------------------- /python/49-Group-Anagrams.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 3 | ans = collections.defaultdict(list) 4 | 5 | for s in strs: 6 | count = [0] * 26 7 | for c in s: 8 | count[ord(c) - ord("a")] += 1 9 | ans[tuple(count)].append(s) 10 | return ans.values() 11 | -------------------------------------------------------------------------------- /python/50-Pow(x, n).py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myPow(self, x: float, n: int) -> float: 3 | def helper(x, n): 4 | if x == 0: 5 | return 0 6 | if n == 0: 7 | return 1 8 | 9 | res = helper(x * x, n // 2) 10 | return x * res if n % 2 else res 11 | 12 | res = helper(x, abs(n)) 13 | return res if n >= 0 else 1 / res 14 | -------------------------------------------------------------------------------- /python/509-Fibonacci-Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | Memo = {} 3 | 4 | def fib(self, n: int): 5 | if n in self.Memo: 6 | return self.Memo[n] 7 | if n == 0: 8 | return 0 9 | if n == 1: 10 | return 1 11 | self.Memo[n] = self.fib(n - 1) + self.fib(n - 2) 12 | return self.Memo[n] 13 | -------------------------------------------------------------------------------- /python/53-Maximum-Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArray(self, nums: List[int]) -> int: 3 | res = nums[0] 4 | 5 | total = 0 6 | for n in nums: 7 | total += n 8 | res = max(res, total) 9 | if total < 0: 10 | total = 0 11 | return res 12 | -------------------------------------------------------------------------------- /python/55-Jump-Game.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canJump(self, nums: List[int]) -> bool: 3 | goal = len(nums) - 1 4 | 5 | for i in range(len(nums) - 2, -1, -1): 6 | if i + nums[i] >= goal: 7 | goal = i 8 | return goal == 0 9 | -------------------------------------------------------------------------------- /python/56-Merge-Intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, intervals: List[List[int]]) -> List[List[int]]: 3 | intervals.sort(key=lambda pair: pair[0]) 4 | output = [intervals[0]] 5 | 6 | for start, end in intervals: 7 | lastEnd = output[-1][1] 8 | 9 | if start <= lastEnd: 10 | # merge 11 | output[-1][1] = max(lastEnd, end) 12 | else: 13 | output.append([start, end]) 14 | return output 15 | -------------------------------------------------------------------------------- /python/58-Length-Of-Last-Word.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLastWord(self, s: str) -> int: 3 | """ 4 | one shortcut 5 | """ 6 | # return len(s.split()[-1]) 7 | c = 0 8 | for i in s[::-1]: 9 | if i == " ": 10 | if c >= 1: 11 | return c 12 | else: 13 | c += 1 14 | return c 15 | -------------------------------------------------------------------------------- /python/62-Unique-Paths.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePaths(self, m: int, n: int) -> int: 3 | row = [1] * n 4 | 5 | for i in range(m - 1): 6 | newRow = [1] * n 7 | for j in range(n - 2, -1, -1): 8 | newRow[j] = newRow[j + 1] + row[j] 9 | row = newRow 10 | return row[0] 11 | 12 | # O(n * m) O(n) 13 | -------------------------------------------------------------------------------- /python/647-Palindromic-Substrings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSubstrings(self, s: str) -> int: 3 | res = 0 4 | 5 | for i in range(len(s)): 6 | res += self.countPali(s, i, i) 7 | res += self.countPali(s, i, i + 1) 8 | return res 9 | 10 | def countPali(self, s, l, r): 11 | res = 0 12 | while l >= 0 and r < len(s) and s[l] == s[r]: 13 | res += 1 14 | l -= 1 15 | r += 1 16 | return res 17 | -------------------------------------------------------------------------------- /python/66-Plus-One.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def plusOne(self, digits: List[int]) -> List[int]: 3 | one = 1 4 | i = 0 5 | digits = digits[::-1] 6 | 7 | while one: 8 | if i < len(digits): 9 | if digits[i] == 9: 10 | digits[i] = 0 11 | else: 12 | digits[i] += 1 13 | one = 0 14 | else: 15 | digits.append(one) 16 | one = 0 17 | i += 1 18 | return digits[::-1] 19 | -------------------------------------------------------------------------------- /python/70-Climbing-Stairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def climbStairs(self, n: int) -> int: 3 | if n <= 3: 4 | return n 5 | n1, n2 = 2, 3 6 | 7 | for i in range(4, n + 1): 8 | temp = n1 + n2 9 | n1 = n2 10 | n2 = temp 11 | return n2 12 | -------------------------------------------------------------------------------- /python/703-Kth-Largest-Element-in-a-Stream.py: -------------------------------------------------------------------------------- 1 | class KthLargest: 2 | def __init__(self, k: int, nums: List[int]): 3 | # minHeap w/ K largest integers 4 | self.minHeap, self.k = nums, k 5 | heapq.heapify(self.minHeap) 6 | while len(self.minHeap) > k: 7 | heapq.heappop(self.minHeap) 8 | 9 | def add(self, val: int) -> int: 10 | heapq.heappush(self.minHeap, val) 11 | if len(self.minHeap) > self.k: 12 | heapq.heappop(self.minHeap) 13 | return self.minHeap[0] 14 | -------------------------------------------------------------------------------- /python/704-Binary-Search.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> int: 3 | l, r = 0, len(nums) - 1 4 | 5 | while l <= r: 6 | m = l + ((r - l) // 2) # (l + r) // 2 can lead to overflow 7 | if nums[m] > target: 8 | r = m - 1 9 | elif nums[m] < target: 10 | l = m + 1 11 | else: 12 | return m 13 | return -1 14 | -------------------------------------------------------------------------------- /python/724-Find-Pivot-Index.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def pivotIndex(self, nums: List[int]) -> int: 3 | total = sum(nums) # O(n) 4 | 5 | leftSum = 0 6 | for i in range(len(nums)): 7 | rightSum = total - nums[i] - leftSum 8 | if leftSum == rightSum: 9 | return i 10 | leftSum += nums[i] 11 | return -1 12 | -------------------------------------------------------------------------------- /python/739-Daily-Temperatures.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def dailyTemperatures(self, temperatures: List[int]) -> List[int]: 3 | res = [0] * len(temperatures) 4 | stack = [] # pair: [temp, index] 5 | 6 | for i, t in enumerate(temperatures): 7 | while stack and t > stack[-1][0]: 8 | stackT, stackInd = stack.pop() 9 | res[stackInd] = i - stackInd 10 | stack.append((t, i)) 11 | return res 12 | -------------------------------------------------------------------------------- /python/746-Min-Cost-Climbing-Stairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minCostClimbingStairs(self, cost: List[int]) -> int: 3 | for i in range(len(cost) - 3, -1, -1): 4 | cost[i] += min(cost[i + 1], cost[i + 2]) 5 | 6 | return min(cost[0], cost[1]) 7 | -------------------------------------------------------------------------------- /python/78-Subsets.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsets(self, nums: List[int]) -> List[List[int]]: 3 | res = [] 4 | 5 | subset = [] 6 | 7 | def dfs(i): 8 | if i >= len(nums): 9 | res.append(subset.copy()) 10 | return 11 | # decision to include nums[i] 12 | subset.append(nums[i]) 13 | dfs(i + 1) 14 | # decision NOT to include nums[i] 15 | subset.pop() 16 | dfs(i + 1) 17 | 18 | dfs(0) 19 | return res 20 | -------------------------------------------------------------------------------- /python/853-Car-Fleet.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: 3 | pair = [(p, s) for p, s in zip(position, speed)] 4 | pair.sort(reverse=True) 5 | stack = [] 6 | for p, s in pair: # Reverse Sorted Order 7 | stack.append((target - p) / s) 8 | if len(stack) >= 2 and stack[-1] <= stack[-2]: 9 | stack.pop() 10 | return len(stack) 11 | -------------------------------------------------------------------------------- /python/875-Koko-Eating-Bananas.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minEatingSpeed(self, piles: List[int], h: int) -> int: 3 | l, r = 1, max(piles) 4 | res = max(piles) 5 | 6 | while l <= r: 7 | k = (l + r) // 2 8 | 9 | totalTime = 0 10 | for p in piles: 11 | totalTime += math.ceil(p / k) 12 | if totalTime <= h: 13 | res = min(res, k) 14 | r = k - 1 15 | else: 16 | l = k + 1 17 | return res 18 | -------------------------------------------------------------------------------- /python/901-Online-Stock-Span.py: -------------------------------------------------------------------------------- 1 | class StockSpanner: 2 | def __init__(self): 3 | self.stack = [] # pair: (price, span) 4 | 5 | def next(self, price: int) -> int: 6 | span = 1 7 | while self.stack and self.stack[-1][0] <= price: 8 | span += self.stack[-1][1] 9 | self.stack.pop() 10 | self.stack.append((price, span)) 11 | return span 12 | -------------------------------------------------------------------------------- /python/973-K-Closest-Points-to-Origin.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: 3 | pts = [] 4 | for x, y in points: 5 | dist = (abs(x - 0) ** 2) + (abs(y - 0) ** 2) 6 | pts.append([dist, x, y]) 7 | 8 | res = [] 9 | heapq.heapify(pts) 10 | for i in range(k): 11 | dist, x, y = heapq.heappop(pts) 12 | res.append([x, y]) 13 | return res 14 | -------------------------------------------------------------------------------- /python/977-Squares-Of-A-Sorted-Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortedSquares(self, nums: List[int]) -> List[int]: 3 | res = [] 4 | for i in nums: 5 | res.append(i*i) 6 | return sorted(res) 7 | # return sorted([x**2 for x in nums]) 8 | -------------------------------------------------------------------------------- /python/Split a String in Balanced Strings: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def balancedStringSplit(self, s: str) -> int: 3 | c=cl=cr=0 4 | for i in s: 5 | if i == "R": 6 | cr +=1 7 | elif i == "L": 8 | cl+=1 9 | if cr==cl: 10 | c+=1 11 | return c 12 | -------------------------------------------------------------------------------- /python/leetcode Two Sum_1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | dict = {} 4 | for i, v in enumerate(nums): 5 | if target - v not in dict: 6 | dict[v] = i 7 | else: 8 | return [dict[target - v], i] 9 | -------------------------------------------------------------------------------- /python/leetcode my calendar III_732.py: -------------------------------------------------------------------------------- 1 | from sortedcontainers import SortedDict 2 | 3 | 4 | class MyCalendarThree: 5 | def __init__(self): 6 | self.timeline = SortedDict() 7 | 8 | def book(self, start: int, end: int) -> int: 9 | self.timeline[start] = self.timeline.get(start, 0) + 1 10 | self.timeline[end] = self.timeline.get(end, 0) - 1 11 | 12 | ans = 0 13 | activeEvents = 0 14 | 15 | for count in self.timeline.values(): 16 | activeEvents += count 17 | ans = max(ans, activeEvents) 18 | -------------------------------------------------------------------------------- /ruby/0053-Maximum-Subarray.rb: -------------------------------------------------------------------------------- 1 | def max_sub_array(nums) 2 | sum = 0 3 | max = -10 * 10 * 10 * 10 - 1 4 | 5 | nums.each do |num| 6 | sum += num 7 | max = sum > max ? sum : max 8 | 9 | sum = 0 if sum < 0 10 | end 11 | 12 | max 13 | end 14 | -------------------------------------------------------------------------------- /ruby/1-Two-Sum.rb: -------------------------------------------------------------------------------- 1 | def two_sum(nums, target) 2 | hash = {} 3 | nums.each_with_index do |num, idx| 4 | return [hash[num], idx] if hash.key? num 5 | 6 | hash[target - num] = idx 7 | end 8 | nil 9 | end 10 | -------------------------------------------------------------------------------- /ruby/100-Same-Tree.rb: -------------------------------------------------------------------------------- 1 | def is_same_tree(p, q) 2 | if p.nil? && q.nil? 3 | true 4 | elsif p && q 5 | (p.val == q.val) && 6 | is_same_tree(p.left, q.left) && 7 | is_same_tree(p.right, q.right) 8 | else 9 | false 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /ruby/104-Maximum-Depth-of-Binary-Tree.rb: -------------------------------------------------------------------------------- 1 | def max_depth(root) 2 | return 0 if root.nil? 3 | return 1 if root.left.nil? && root.right.nil? 4 | 5 | left = 1 + max_depth(root.left) 6 | right = 1 + max_depth(root.right) 7 | left > right ? left : right 8 | end 9 | -------------------------------------------------------------------------------- /ruby/1046-Last-Stone-Weight.rb: -------------------------------------------------------------------------------- 1 | require "rubygems" 2 | require "algorithms" 3 | include Containers 4 | 5 | def last_stone_weight(stones) 6 | heap = MaxHeap.new 7 | stones.each { |stone| heap << stone } 8 | until heap.size <= 1 9 | stone1 = heap.pop 10 | stone2 = heap.pop 11 | heap << (stone1 - stone2).abs if stone1 != stone2 12 | end 13 | last = heap.pop 14 | last.nil? ? 0 : last 15 | end 16 | -------------------------------------------------------------------------------- /ruby/11-Container-With-Most-Water.rb: -------------------------------------------------------------------------------- 1 | def max_area(height) 2 | idx_start = 0 3 | idx_end = height.length - 1 4 | max_water = 0 5 | while idx_start < idx_end 6 | challenger = (height[idx_start] > height[idx_end] ? height[idx_end] : height[idx_start]) 7 | challenger *= (idx_end - idx_start) 8 | max_water = challenger if challenger > max_water 9 | 10 | if height[idx_start] > height[idx_end] 11 | idx_end -= 1 12 | else 13 | idx_start += 1 14 | end 15 | end 16 | max_water 17 | end 18 | -------------------------------------------------------------------------------- /ruby/110-Balanced-Binary-Tree.rb: -------------------------------------------------------------------------------- 1 | def is_balanced(root) 2 | $balance = true 3 | balanced?(root) 4 | $balance 5 | end 6 | 7 | def balanced?(root) 8 | return -1 if root.nil? 9 | 10 | left_height = 1 + balanced?(root.left) 11 | right_height = 1 + balanced?(root.right) 12 | $balance = false if (left_height - right_height).abs > 1 13 | 14 | left_height > right_height ? left_height : right_height 15 | end 16 | -------------------------------------------------------------------------------- /ruby/121-Best-Time-To-Buy-and-Sell-Stock.rb: -------------------------------------------------------------------------------- 1 | def max_profit(prices) 2 | max_profit = 0 3 | min = prices.first 4 | prices.each do |price| 5 | min = price if price < min 6 | profit = price - min 7 | max_profit = profit if profit > max_profit 8 | end 9 | max_profit 10 | end 11 | -------------------------------------------------------------------------------- /ruby/136-Single-Number.rb: -------------------------------------------------------------------------------- 1 | def single_number(nums) 2 | nums.inject { |accu, num| accu ^ num } 3 | end 4 | -------------------------------------------------------------------------------- /ruby/155-Min-Stack.rb: -------------------------------------------------------------------------------- 1 | class MinStack 2 | def initialize 3 | @stack = [] 4 | end 5 | 6 | def push(val) 7 | min = if @stack.empty? 8 | val 9 | else 10 | val < @stack.last[1] ? val : @stack.last[1] 11 | end 12 | 13 | @stack << [val, min] 14 | nil 15 | end 16 | 17 | def pop 18 | @stack.pop 19 | nil 20 | end 21 | 22 | def top 23 | return nil if @stack.empty? 24 | 25 | @stack.last[0] 26 | end 27 | 28 | def get_min 29 | return nil if @stack.empty? 30 | 31 | @stack.last[1] 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /ruby/167-Two-Sum-II.rb: -------------------------------------------------------------------------------- 1 | def two_sum(numbers, target) 2 | idx_start = 0 3 | idx_end = numbers.length - 1 4 | while idx_start < idx_end 5 | case numbers[idx_start] + numbers[idx_end] <=> target 6 | when 1 7 | idx_end -= 1 8 | when 0 9 | return [idx_start + 1, idx_end + 1] 10 | when -1 11 | idx_start += 1 12 | end 13 | end 14 | nil 15 | end 16 | -------------------------------------------------------------------------------- /ruby/190-Reverse-Bits.rb: -------------------------------------------------------------------------------- 1 | def reverse_bits(n) 2 | reversed_bits = 0 3 | 31.downto(0) do |nbr| 4 | insert = ((n >> (31 - nbr)) & 1) << nbr 5 | reversed_bits |= insert 6 | end 7 | reversed_bits 8 | end 9 | -------------------------------------------------------------------------------- /ruby/191-Number-of-1-Bits.rb: -------------------------------------------------------------------------------- 1 | def hamming_weight(n) 2 | total_ones = 0 3 | until n.zero? 4 | total_ones += (n % 2) 5 | n = n >> 1 6 | end 7 | total_ones 8 | end 9 | 10 | # Solution utilizing & (n - 1) 11 | def hamming_weight(n) 12 | total_ones = 0 13 | until n.zero? 14 | n &= (n - 1) 15 | total_ones += 1 16 | end 17 | total_ones 18 | end 19 | -------------------------------------------------------------------------------- /ruby/198-House-Robber.rb: -------------------------------------------------------------------------------- 1 | # @param {Integer[]} nums 2 | # @return {Integer} 3 | def rob(nums) 4 | dp = Array.new(nums.size + 3) { 0 } 5 | 6 | nums.each_with_index do |num, i| 7 | dp[i + 3] = num + [dp[i + 1], dp[i]].max 8 | end 9 | 10 | [dp[-1], dp[-2]].max 11 | end 12 | -------------------------------------------------------------------------------- /ruby/20-Valid-Parentheses.rb: -------------------------------------------------------------------------------- 1 | def is_valid(s) 2 | paren = [] 3 | match = { 4 | "{" => "}", 5 | "(" => ")", 6 | "[" => "]", 7 | } 8 | s.each_char do |char| 9 | if match.key?(char) 10 | paren << char 11 | else 12 | return false if paren.empty? 13 | return false if match[paren.pop] != char 14 | end 15 | end 16 | paren.empty? 17 | end 18 | -------------------------------------------------------------------------------- /ruby/206-Reverse-Linked-List.rb: -------------------------------------------------------------------------------- 1 | def reverse_list(head) 2 | next_node = nil 3 | prev_node = nil 4 | loop do 5 | next_node = head.next 6 | head.next = prev_node 7 | prev_node = head 8 | if next_node.nil? 9 | return head 10 | else 11 | head = next_node 12 | end 13 | end 14 | end 15 | 16 | # Recursive 17 | def reverse_list(head) 18 | return head if head.nil? 19 | 20 | new_head = head 21 | if head.next 22 | new_head = reverse_list(head.next) 23 | head.next.next = head 24 | end 25 | 26 | head.next = nil 27 | new_head 28 | end 29 | -------------------------------------------------------------------------------- /ruby/21-Merge-Two-Sorted-Lists.rb: -------------------------------------------------------------------------------- 1 | def merge_two_lists(list1, list2) 2 | return nil if list1.nil? && list2.nil? 3 | 4 | dummy = ListNode.new 5 | beginning = dummy 6 | while list1 && list2 7 | if list1.val > list2.val 8 | dummy.next = list2 9 | list2 = list2.next 10 | else 11 | dummy.next = list1 12 | list1 = list1.next 13 | end 14 | dummy = dummy.next 15 | end 16 | if list1 17 | dummy.next = list1 18 | elsif list2 19 | dummy.next = list2 20 | end 21 | beginning.next 22 | end 23 | -------------------------------------------------------------------------------- /ruby/217-Contains-Duplicate.rb: -------------------------------------------------------------------------------- 1 | def contains_duplicate(nums) 2 | hash = {} 3 | nums.each do |num| 4 | return true if hash.key? num 5 | 6 | hash[num] = true 7 | end 8 | false 9 | end 10 | -------------------------------------------------------------------------------- /ruby/226-Invert-Binary-Tree.rb: -------------------------------------------------------------------------------- 1 | def invert_tree(root) 2 | return root if root.nil? 3 | return root if root.left.nil? && root.right.nil? 4 | 5 | root.left, root.right = root.right, root.left 6 | invert_tree(root.left) 7 | invert_tree(root.right) 8 | root 9 | end 10 | -------------------------------------------------------------------------------- /ruby/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.rb: -------------------------------------------------------------------------------- 1 | def lowest_common_ancestor(root, p, q) 2 | return root if root.val == p.val || root.val == q.val 3 | return root if root.val.between?(p.val, q.val) || root.val.between?(q.val, p.val) 4 | 5 | if root.val > p.val 6 | lowest_common_ancestor(root.left, p, q) 7 | else 8 | lowest_common_ancestor(root.right, p, q) 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /ruby/242-Valid-Anagrams.rb: -------------------------------------------------------------------------------- 1 | def is_anagram(s, t) 2 | return false unless s.length == t.length 3 | 4 | hash = Hash.new(0) 5 | s.each_char.with_index do |_, idx| 6 | hash[s[idx]] += 1 7 | hash[t[idx]] -= 1 8 | end 9 | hash.all? { |_k, v| v.zero? } 10 | end 11 | 12 | # For nlogn time and O(1) space, can sort then check if equal 13 | def is_anagram(s, t) 14 | s.chars.sort.join == t.chars.sort.join 15 | end 16 | -------------------------------------------------------------------------------- /ruby/268-Missing-Number.rb: -------------------------------------------------------------------------------- 1 | def missing_number(nums) 2 | missing = 0 3 | (0..nums.length).each do |i| 4 | nbr = (nums[i].nil? ? 0 : nums[i]) 5 | missing += (i - nbr) 6 | end 7 | missing 8 | end 9 | 10 | # Solution using Gauss summation 11 | def missing_number(nums) 12 | gauss = (nums.length / 2.0) * (nums.length + 1) 13 | nums.each { |n| gauss -= n } 14 | gauss.to_i 15 | end 16 | -------------------------------------------------------------------------------- /ruby/3-Longest-Substring-Without-Repeating-Characters.rb: -------------------------------------------------------------------------------- 1 | def length_of_longest_substring(s) 2 | return 1 if s.length == 1 3 | return 0 if s.length.zero? 4 | 5 | window = [] 6 | appear = {} 7 | max = 0 8 | s.each_char do |c| 9 | if appear.key?(c) 10 | while appear.key?(c) 11 | appear.delete(window.shift) 12 | end 13 | end 14 | window << c 15 | appear[c] = c 16 | max = window.length if window.length > max 17 | end 18 | max 19 | end 20 | -------------------------------------------------------------------------------- /ruby/338-Counting-Bits.rb: -------------------------------------------------------------------------------- 1 | def count_bits(n) 2 | bits = [] 3 | offset = 2 4 | (n + 1).times do |nbr| 5 | bits << if nbr <= 2 || nbr == (offset * 2) 6 | nbr.zero? ? 0 : 1 7 | else 8 | (bits[offset] + bits[nbr - offset]) 9 | end 10 | 11 | offset *= 2 if nbr == offset * 2 12 | end 13 | bits 14 | end 15 | -------------------------------------------------------------------------------- /ruby/347-Top-k-frequent-elements.rb: -------------------------------------------------------------------------------- 1 | def top_k_frequent(nums, k) 2 | hash = Hash.new(0) 3 | max_freq = 0 4 | nums.each do |num| 5 | hash[num] += 1 6 | max_freq = hash[num] if hash[num] > max_freq 7 | end 8 | counts = Array.new(max_freq + 1) { [] } 9 | hash.each { |k, v| counts[v] << k } 10 | top_k = [] 11 | max_freq.downto(1) do |n| 12 | return top_k if k <= 0 13 | next if counts[n].empty? 14 | 15 | top_k.concat(counts[n].take(k)) 16 | k -= counts[n].length 17 | end 18 | top_k 19 | end 20 | -------------------------------------------------------------------------------- /ruby/49-Group-Anagrams.rb: -------------------------------------------------------------------------------- 1 | def group_anagrams(strs) 2 | anagrams = Hash.new { |h, k| h[k] = [] } 3 | strs.each do |str| 4 | hash = Hash.new(0) 5 | str.each_char { |c| hash[c] += 1 } 6 | anagrams[hash] << str 7 | end 8 | anagrams.values 9 | end 10 | -------------------------------------------------------------------------------- /ruby/543-Diameter-of-Binary-Tree.rb: -------------------------------------------------------------------------------- 1 | def diameter_of_binary_tree(root) 2 | $max = 0 3 | max_height = diameter(root) 4 | $max > max_height ? $max : max_height 5 | end 6 | 7 | def diameter(root) 8 | return -1 if root.nil? 9 | 10 | left = 1 + diameter(root.left) 11 | right = 1 + diameter(root.right) 12 | diameter = left + right 13 | $max = diameter if diameter > $max 14 | 15 | left > right ? left : right 16 | end 17 | -------------------------------------------------------------------------------- /ruby/572-Subtree-of-Another-Tree.rb: -------------------------------------------------------------------------------- 1 | def is_subtree(root, sub_root) 2 | return true if root.nil? && sub_root.nil? 3 | return true if sub_root.nil? 4 | return false if root.nil? 5 | 6 | if same_tree?(root, sub_root) 7 | true 8 | else 9 | is_subtree(root.left, sub_root) || 10 | is_subtree(root.right, sub_root) 11 | end 12 | end 13 | 14 | def same_tree?(p, q) 15 | if p.nil? && q.nil? 16 | true 17 | elsif p && q 18 | (p.val == q.val) && 19 | same_tree?(p.left, q.left) && 20 | same_tree?(p.right, q.right) 21 | else 22 | false 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /ruby/7-Reverse-Integer.rb: -------------------------------------------------------------------------------- 1 | def reverse(x) 2 | max = 0xffffffff >> 1 3 | max_last_digit = max % 10 4 | max_minus_digit = max / 10 5 | reverse = 0 6 | until x.zero? 7 | digit = x.remainder(10) 8 | return 0 if reverse.abs > max_minus_digit || (reverse.abs == max_minus_digit && digit > max_last_digit) 9 | 10 | reverse = (reverse * 10) + digit 11 | x = (x / 10.0).to_i 12 | end 13 | reverse 14 | end 15 | -------------------------------------------------------------------------------- /ruby/703-Kth-Largest-Element-in-a-Stream.rb: -------------------------------------------------------------------------------- 1 | require "rb_heap" 2 | 3 | class KthLargest 4 | def initialize(k, nums) 5 | @k = k 6 | @heap = Heap.new 7 | nums.each { |num| @heap << num } 8 | @heap.pop until @heap.size <= @k 9 | end 10 | 11 | def add(val) 12 | @heap << val 13 | @heap.pop until @heap.size <= @k 14 | @heap.peak 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /ruby/746-Min-Cost-Climbing-Stairs.rb: -------------------------------------------------------------------------------- 1 | def min_cost_climbing_stairs(cost) 2 | return 0 if cost.empty? 3 | return cost.first if cost.length == 1 4 | 5 | second = 0 6 | first = cost[-1] 7 | (cost.length - 2).downto(0) do |idx| 8 | cost1 = cost[idx] + first 9 | cost2 = cost[idx] + second 10 | tmp = cost1 > cost2 ? cost2 : cost1 11 | second = first 12 | first = tmp 13 | end 14 | first > second ? second : first 15 | end 16 | -------------------------------------------------------------------------------- /ruby/78-Subsets.rb: -------------------------------------------------------------------------------- 1 | # @param {Integer[]} nums 2 | # @return {Integer[][]} 3 | def subsets(nums) 4 | ans = [] 5 | 6 | recurse(nums, ans, [], 0) 7 | 8 | ans 9 | end 10 | 11 | 12 | def recurse(nums, ans, curr, i) 13 | if i == nums.length 14 | ans << curr.clone 15 | return 16 | end 17 | 18 | 19 | curr << nums[i] 20 | recurse(nums, ans, curr, i + 1) 21 | 22 | curr.pop 23 | recurse(nums, ans, curr, i + 1) 24 | end 25 | -------------------------------------------------------------------------------- /rust/1-Two-Sum.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | impl Solution { 4 | pub fn two_sum(nums: Vec, target: i32) -> Vec { 5 | let mut map = HashMap::new(); 6 | 7 | for (i, n) in nums.into_iter().enumerate(){ 8 | let diff = target - n; 9 | 10 | if let Some(&j) = map.get(&diff){ 11 | return vec![i as i32, j as i32]; 12 | }else{ 13 | map.insert(n, i); 14 | } 15 | } 16 | 17 | unreachable!() 18 | } 19 | } -------------------------------------------------------------------------------- /rust/121-Best-Time-To-Buy.rs: -------------------------------------------------------------------------------- 1 | use std::cmp; 2 | 3 | impl Solution { 4 | pub fn max_profit(prices: Vec) -> i32 { 5 | let mut l = 0; 6 | let mut r = 1; 7 | let mut max_profit = 0; 8 | 9 | while r < prices.len() { 10 | if prices[l] < prices[r] { 11 | let profit = prices[r] - prices[l]; 12 | max_profit = cmp::max(profit, max_profit); 13 | } else { 14 | l = r; 15 | } 16 | r += 1; 17 | } 18 | 19 | max_profit 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /rust/125-Valid-Palindrome.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn is_palindrome(s: String) -> bool { 3 | let s: Vec = s.chars() 4 | .filter(|c| c.is_alphanumeric()) 5 | .map(|c| c.to_lowercase().next().unwrap()) 6 | .collect(); 7 | 8 | let len = s.len(); 9 | 10 | for i in 0..(len/2){ 11 | if s[i] != s[len - i - 1]{ 12 | return false 13 | } 14 | } 15 | 16 | true 17 | } 18 | } -------------------------------------------------------------------------------- /rust/167-Two-Sum-II.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn two_sum(numbers: Vec, target: i32) -> Vec { 3 | let (mut l, mut r) = (0, numbers.len() - 1); 4 | 5 | while l < r{ 6 | let sum = numbers[l] + numbers[r]; 7 | 8 | if sum > target{ 9 | r-=1; 10 | }else if sum < target{ 11 | l+=1; 12 | }else{ 13 | return vec![(l + 1) as i32, (r + 1) as i32]; 14 | } 15 | } 16 | 17 | unreachable!() 18 | } 19 | } -------------------------------------------------------------------------------- /rust/198-House-Robber.rs: -------------------------------------------------------------------------------- 1 | // time complexity: O(n) 2 | // space complexity: O(1) 3 | 4 | impl Solution { 5 | pub fn rob(mut nums: Vec) -> i32 { 6 | if nums.len() == 1{ 7 | return nums[0]; 8 | } 9 | 10 | nums[1] = nums[0].max(nums[1]); 11 | 12 | for i in 2..nums.len(){ 13 | nums[i] = nums[i-1].max(nums[i - 2] + nums[i]); 14 | } 15 | 16 | *nums.last().unwrap() 17 | } 18 | } -------------------------------------------------------------------------------- /rust/217-Contains-Duplicates.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashSet; 2 | 3 | impl Solution { 4 | pub fn contains_duplicate(nums: Vec) -> bool { 5 | let mut map = HashSet::new(); 6 | 7 | for &n in nums.iter(){ 8 | 9 | if map.contains(&n){ 10 | return true; 11 | } 12 | 13 | map.insert(n); 14 | }; 15 | 16 | false 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /rust/238-Product-Of-Array-Except-Self.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn product_except_self(mut nums: Vec) -> Vec { 3 | let mut res = vec![1; nums.len()]; 4 | 5 | for i in (1..nums.len()){ 6 | res[i] = nums[i - 1] * res[i - 1]; 7 | } 8 | 9 | let mut right = 1; 10 | 11 | for (i, n) in res.iter_mut().enumerate().rev(){ 12 | *n = *n * right; 13 | right *= nums[i]; 14 | } 15 | 16 | res 17 | } 18 | } -------------------------------------------------------------------------------- /rust/242-Valid-Anagram.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | impl Solution { 4 | pub fn is_anagram(s: String, t: String) -> bool { 5 | if (t.len() != s.len()){ 6 | return false; 7 | } 8 | 9 | let mut map: HashMap = HashMap::new(); 10 | 11 | for (a, b) in s.chars().zip(t.chars()){ 12 | *map.entry(a).or_default() +=1; 13 | *map.entry(b).or_default() -=1; 14 | } 15 | 16 | map.into_values().all(|cnt| cnt == 0) 17 | } 18 | } -------------------------------------------------------------------------------- /rust/70-Climbing-Stairs.rs: -------------------------------------------------------------------------------- 1 | 2 | impl Solution { 3 | pub fn climb_stairs(n: i32) -> i32 { 4 | if n == 1{ 5 | return 1; 6 | } 7 | 8 | let (mut one, mut two) = (1, 2); 9 | 10 | for i in 2..n{ 11 | let tmp = two; 12 | two = two + one; 13 | one = tmp; 14 | } 15 | 16 | two 17 | } 18 | } -------------------------------------------------------------------------------- /rust/746-Min-Cost-Climbing-Stairs.rs: -------------------------------------------------------------------------------- 1 | // time compexity : O(n) 2 | // space compexity : O(1) 3 | 4 | impl Solution { 5 | pub fn min_cost_climbing_stairs(mut cost: Vec) -> i32 { 6 | for i in 2..cost.len(){ 7 | cost[i] += cost[i- 1].min(cost[i-2]); 8 | } 9 | 10 | let len = cost.len(); 11 | 12 | cost[len - 1].min(cost[len - 2]) 13 | } 14 | } -------------------------------------------------------------------------------- /scala/198-House-Robber.scala: -------------------------------------------------------------------------------- 1 | object Solution { 2 | def rob(nums: Array[Int]): Int = { 3 | var (prevTwoMaxProfit, prevMaxProfit) = (0, 0) 4 | 5 | for (currCash <- nums) { 6 | val currProfit = (currCash + prevTwoMaxProfit).max(prevMaxProfit) 7 | prevTwoMaxProfit = prevMaxProfit 8 | prevMaxProfit = currProfit 9 | } 10 | 11 | return prevMaxProfit 12 | } 13 | } -------------------------------------------------------------------------------- /scala/206-Reverse-Linked-List.scala: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode(_x: Int = 0, _next: ListNode = null) { 4 | * var next: ListNode = _next 5 | * var x: Int = _x 6 | * } 7 | */ 8 | object Solution { 9 | def reverseList(head: ListNode): ListNode = { 10 | if (head == null || head.next == null) { 11 | return head 12 | } 13 | 14 | val reversedListHead = reverseList(head.next) 15 | head.next.next = head 16 | head.next = null 17 | 18 | return reversedListHead 19 | } 20 | } -------------------------------------------------------------------------------- /scala/217-Contains-Duplicate.scala: -------------------------------------------------------------------------------- 1 | import scala.collection.mutable.HashSet 2 | 3 | object Solution { 4 | def containsDuplicate(nums: Array[Int]): Boolean = { 5 | var seen: HashSet[Int] = HashSet() 6 | for (num <- nums) { 7 | if (seen.contains(num)) return true 8 | seen.add(num) 9 | } 10 | return false 11 | } 12 | } -------------------------------------------------------------------------------- /swift/1-Two-Sum.swift: -------------------------------------------------------------------------------- 1 | /** 2 | * Question Link: https://leetcode.com/problems/two-sum/ 3 | */ 4 | 5 | class TwoSum { 6 | func twoSum(_ nums: [Int], _ target: Int) -> [Int] { 7 | var prevMap = [Int:Int]() // val -> index 8 | 9 | for (i, n) in nums.enumerated() { 10 | let diff = target - n 11 | if let firstIndex = prevMap[diff] { 12 | return [firstIndex, i] 13 | } 14 | prevMap[n] = i 15 | } 16 | return [] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /swift/100-Same-Tree.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool { 3 | if p == nil && q == nil { return true } 4 | if p?.val != q?.val { return false } 5 | return isSameTree(p?.left, q?.left) && isSameTree(p?.right, q?.right) 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /swift/104-Maximum-Depth-of-Binary-Tree.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func maxDepth(_ root: TreeNode?) -> Int { 3 | guard root != nil else { return 0 } 4 | return max(maxDepth(root?.left) + 1, maxDepth(root?.right) + 1) 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /swift/11-Container-With-Most-Water.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func maxArea(_ height: [Int]) -> Int { 3 | var maxArea = 0 4 | var l = 0 5 | var r = height.count - 1 6 | while l < r { 7 | let lV = height[l] 8 | let rV = height[r] 9 | let area = (r - l) * min(rV, lV) 10 | maxArea = max(area, maxArea) 11 | l += lV < rV ? 1 : 0 12 | r -= lV >= rV ? 1 : 0 13 | } 14 | return maxArea 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /swift/121-Best-Time-to-Buy-and-Sell-Stock.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func maxProfit(_ prices: [Int]) -> Int { 3 | var res = 0 4 | var l = 0 5 | var r = 0 6 | 7 | for r in 1.. Int { 3 | var res = nums[0] 4 | var curMin = 1 5 | var curMax = 1 6 | 7 | for n in nums { 8 | let temp = curMax * n 9 | curMax = max(n * curMax, n * curMin, n) 10 | curMin = min(temp, n * curMin, n) 11 | res = max(res, curMax) 12 | } 13 | return res 14 | } 15 | } -------------------------------------------------------------------------------- /swift/167-Two-Sum-II-Input-Array-Is-Sorted.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func twoSum(_ numbers: [Int], _ target: Int) -> [Int] { 3 | var rp = numbers.count - 1 4 | var lp = 0 5 | while lp < rp { 6 | if numbers[lp] + numbers[rp] == target { 7 | return [lp + 1, rp + 1] 8 | } 9 | if numbers[lp] + numbers[rp] > target { 10 | rp -= 1 11 | } else { 12 | lp += 1 13 | } 14 | } 15 | return [] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /swift/190-Reverse-Bits.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func reverseBits(_ n: Int) -> Int { 3 | var res = 0 4 | 5 | for i in 0...31 { 6 | let bit = (n >> i) & 1 7 | res = res | (bit << (31 - i)) 8 | } 9 | return res 10 | } 11 | } -------------------------------------------------------------------------------- /swift/191-Number-of-1-Bits.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func hammingWeight(_ n: Int) -> Int { 3 | var x = n 4 | var count = 0 5 | while x != 0 { 6 | x = x & (x - 1) 7 | count += 1 8 | } 9 | return count 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /swift/198-House-Robber.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func rob(_ nums: [Int]) -> Int { 3 | var rob1 = 0, rob2 = 0 4 | 5 | for n in nums { 6 | let temp = max(n + rob1, rob2) 7 | rob1 = rob2 8 | rob2 = temp 9 | } 10 | return rob2 11 | } 12 | } -------------------------------------------------------------------------------- /swift/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func lowestCommonAncestor(_ root: TreeNode?, _ p: TreeNode?, _ q: TreeNode?) -> TreeNode? { 3 | guard let root = root, let p = p, let q = q else { return nil } 4 | if root.val < p.val && root.val < q.val { 5 | return lowestCommonAncestor(root.right, p, q) 6 | } else if root.val > p.val && root.val > q.val { 7 | return lowestCommonAncestor(root.left, p, q) 8 | } else { 9 | return root 10 | } 11 | return nil 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /swift/268-Missing-Number.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func missingNumber(_ nums: [Int]) -> Int { 3 | var res = nums.count 4 | 5 | for i in 0...nums.count-1 { 6 | res += i - nums[i] 7 | } 8 | return res 9 | } 10 | } -------------------------------------------------------------------------------- /swift/287-Find-The-Duplicate-Number.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func findDuplicate(_ nums: [Int]) -> Int { 3 | var slow = 0, fast = 0 4 | while true { 5 | slow = nums[slow] 6 | fast = nums[nums[fast]] 7 | if slow == fast { 8 | break 9 | } 10 | } 11 | 12 | var slow2 = 0 13 | while true { 14 | slow = nums[slow] 15 | slow2 = nums[slow2] 16 | if slow == slow2 { 17 | return slow 18 | } 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /swift/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func maxProfit(_ prices: [Int]) -> Int { 3 | var sold = 0, hold = -1000, rest = 0 4 | 5 | for i in 0...prices.count-1 { 6 | let prevSold = sold 7 | sold = hold + prices[i] 8 | hold = max(hold, rest - prices[i]) 9 | rest = max(rest, prevSold) 10 | } 11 | return max(sold, rest) 12 | } 13 | } -------------------------------------------------------------------------------- /swift/338-Counting-Bits.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func countBits(_ n: Int) -> [Int] { 3 | var result: [Int] = [] 4 | for x in 0 ..< n + 1 { 5 | result.append(popCount(x)) 6 | } 7 | return result 8 | } 9 | 10 | func popCount(_ x: Int) -> Int { 11 | var x = x 12 | var count = 0 13 | while x != 0 { 14 | x &= x - 1 15 | count += 1 16 | } 17 | return count 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /swift/371-Sum-Of-Two-Integers.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func getSum(_ a: Int, _ b: Int) -> Int { 3 | var res = a 4 | var secondInt = b 5 | 6 | while secondInt != 0 { 7 | let temp = (res & secondInt) << 1 8 | res ^= secondInt 9 | secondInt = temp 10 | } 11 | return res 12 | } 13 | } -------------------------------------------------------------------------------- /swift/45-Jump-Game-II.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func jump(_ nums: [Int]) -> Int { 3 | var left = 0, right = 0 4 | var res = 0 5 | 6 | while right < nums.count - 1 { 7 | var maxJump = 0 8 | for i in left...right { 9 | maxJump = max(maxJump, i + nums[i]) 10 | } 11 | left = right + 1 12 | right = maxJump 13 | res += 1 14 | } 15 | return res 16 | } 17 | } -------------------------------------------------------------------------------- /swift/49-Group-Anagrams.swift: -------------------------------------------------------------------------------- 1 | /** 2 | * Question Link: https://leetcode.com/problems/anagrams/ 3 | */ 4 | 5 | class GroupAnagrams { 6 | func groupAnagrams(_ strs: [String]) -> [[String]] { 7 | var ans = [[Int]:[String]]() 8 | let a = "a" as Character 9 | 10 | for s in strs { 11 | var count = [Int](repeating: 0, count: 26) 12 | for c in Array(s) { 13 | count[Int(c.asciiValue! - a.asciiValue!)] += 1 14 | } 15 | ans[count, default: []].append(s) 16 | } 17 | return Array(ans.values) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /swift/50-Pow(x, n).swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func myPow(_ x: Double, _ n: Int) -> Double { 3 | func helper(_ x: Double, _ n: Int) -> Double { 4 | if x == 0 { 5 | return 0 6 | } 7 | 8 | if n == 0 { 9 | return 1 10 | } 11 | 12 | var res = helper(x, n/2) 13 | res = res * res 14 | return n % 2 == 1 ? x*res : res 15 | } 16 | 17 | var res = helper(x, abs(n)) 18 | return n >= 0 ? res : 1/res 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /swift/53-Maximum-Subarray.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func maxSubArray(_ nums: [Int]) -> Int { 3 | var res = nums[0] 4 | var total = 0 5 | 6 | for n in nums { 7 | total += n 8 | res = max(res, total) 9 | if total < 0 { 10 | total = 0 11 | } 12 | } 13 | return res 14 | } 15 | } -------------------------------------------------------------------------------- /swift/55-Jump-Game.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func canJump(_ nums: [Int]) -> Bool { 3 | var goal = nums.count - 1 4 | 5 | for i in stride(from: nums.count-2, through: 0, by: -1){ 6 | if i + nums[i] >= goal { 7 | goal = i 8 | } 9 | } 10 | return goal == 0 11 | } 12 | } -------------------------------------------------------------------------------- /swift/66-Plus-One.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func plusOne(_ digits: [Int]) -> [Int] { 3 | // parameters are immutable in swift 4 | var digit = digits 5 | for i in stride(from: digit.count - 1, through: 0, by: -1) { 6 | digit[i] += 1 7 | 8 | if digit[i] <= 9 { 9 | return digit 10 | } 11 | 12 | digit[i] = 0 13 | } 14 | 15 | digit.insert(1, at: 0) 16 | return digit 17 | } 18 | } -------------------------------------------------------------------------------- /swift/70-Climbing-Stairs.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func climbStairs(_ n: Int) -> Int { 3 | if n <= 3 { 4 | return n 5 | } 6 | var n1 = 2 7 | var n2 = 3 8 | 9 | for i in 4...n { 10 | let temp = n1 + n2 11 | n1 = n2 12 | n2 = temp 13 | } 14 | return n2 15 | } 16 | } -------------------------------------------------------------------------------- /swift/704-Binary-Search: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func search(_ nums: [Int], _ target: Int) -> Int { 3 | var l = 0 4 | var r = nums.count - 1 5 | while l <= r { 6 | let mid = (l + r) / 2 7 | guard nums[mid] != target else { return mid } 8 | l = nums[mid] < target ? mid + 1 : l 9 | r = nums[mid] > target ? mid - 1 : r 10 | } 11 | return -1 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /swift/746-Min-Cost-Climbing-Stairs.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func minCostClimbingStairs(_ cost: [Int]) -> Int { 3 | var stepsCost = cost 4 | for i in stride(from: cost.count - 3, through: 0, by: -1) { 5 | stepsCost[i] += min(stepsCost[i + 1], stepsCost[i + 2]) 6 | } 7 | return min(stepsCost[0], stepsCost[1]) 8 | } 9 | } -------------------------------------------------------------------------------- /swift/98-Validate-Binary-Search-Tree.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func isValidBST(_ root: TreeNode?) -> Bool { 3 | return isBst(root, min: Int.min, max: Int.max) 4 | } 5 | 6 | private func isBst(_ node: TreeNode?, min: Int, max: Int) -> Bool { 7 | if node == nil { return true } 8 | if node!.val <= min || node!.val >= max { return false } 9 | let lc = isBst(node?.left, min: min, max: node!.val) 10 | let rc = isBst(node?.right, min: node!.val, max: max) 11 | return lc && rc 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /typescript/1-Two-Sum.ts: -------------------------------------------------------------------------------- 1 | function twoSum(nums: number[], target: number): number[] { 2 | let hash: { [key: number]: number } = {}; 3 | for (let i = 0; i < nums.length; i++) { 4 | let diff = target - nums[i]; 5 | if (diff in hash) { 6 | return [hash[diff], i]; 7 | } else { 8 | hash[nums[i]] = i; 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /typescript/11-Container-With-Most-Water.ts: -------------------------------------------------------------------------------- 1 | function maxArea(height: number[]): number { 2 | let l = 0; 3 | let r = height.length - 1; 4 | let max = 0; 5 | 6 | while (l < r) { 7 | let area = (r - l) * Math.min(height[l], height[r]); 8 | 9 | max = Math.max(max, area); 10 | 11 | if (height[l] < height[r]) { 12 | l += 1; 13 | } else { 14 | r -= 1; 15 | } 16 | } 17 | 18 | return max; 19 | } 20 | -------------------------------------------------------------------------------- /typescript/121-Best-Time-To-Buy-and-Sell-Stock.ts: -------------------------------------------------------------------------------- 1 | function maxProfit(prices: number[]): number { 2 | let max = 0; 3 | let l = 0; 4 | let r = 1; 5 | 6 | while (r < prices.length) { 7 | if (prices[l] < prices[r]) { 8 | let profit = prices[r] - prices[l]; 9 | if (profit > max) { 10 | max = profit; 11 | } 12 | } else { 13 | l = r; 14 | } 15 | r++; 16 | } 17 | 18 | return max; 19 | } 20 | -------------------------------------------------------------------------------- /typescript/125-Valid-Palindrome.ts: -------------------------------------------------------------------------------- 1 | function isPalindrome(s: string): boolean { 2 | const array = s 3 | .toLowerCase() 4 | .replace(/[^A-Za-z0-9]/g, '') 5 | .replace(/\s/g, '') 6 | .split(''); 7 | 8 | for (let i = 0; i < array.length; i++) { 9 | const first = array[i]; 10 | const second = array[array.length - 1 - i]; 11 | 12 | if (first !== second) { 13 | return false; 14 | } 15 | } 16 | return true; 17 | } 18 | -------------------------------------------------------------------------------- /typescript/128-Longest-Consecutive-Sequence.ts: -------------------------------------------------------------------------------- 1 | function longestConsecutive(nums: number[]): number { 2 | const number = new Set(nums); 3 | let longest = 0; 4 | 5 | for (const n of nums) { 6 | if (!number.has(n - 1)) { 7 | let length = 0; 8 | while (number.has(n + length)) { 9 | length += 1; 10 | } 11 | longest = Math.max(length, longest); 12 | } 13 | } 14 | 15 | return longest; 16 | } 17 | -------------------------------------------------------------------------------- /typescript/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.ts: -------------------------------------------------------------------------------- 1 | function replaceElements(arr: number[]): number[] { 2 | let currMax = -1; 3 | 4 | for(let i = arr.length -1 ; i >= 0; i--) { 5 | let newMax = Math.max(currMax, arr[i]); 6 | arr[i] = currMax; 7 | 8 | currMax = newMax; 9 | } 10 | 11 | return arr; 12 | }; 13 | -------------------------------------------------------------------------------- /typescript/136-Single-Number.ts: -------------------------------------------------------------------------------- 1 | function singleNumber(nums: number[]): number { 2 | let res = 0; 3 | 4 | for (let i = 0; i < nums.length; i++) { 5 | res = nums[i] ^ res; 6 | } 7 | 8 | return res; 9 | } 10 | -------------------------------------------------------------------------------- /typescript/139-Word-Break.ts: -------------------------------------------------------------------------------- 1 | function wordBreak(s: string, wordDict: string[]): boolean { 2 | const dp = Array(s.length + 1).fill(false); 3 | 4 | dp[s.length] = true; 5 | 6 | for (let i = s.length - 1; i > -1; i--) { 7 | for (const w of wordDict) { 8 | if (i + w.length <= s.length && s.slice(i, i + w.length) == w) { 9 | dp[i] = dp[i + w.length]; 10 | } 11 | if (dp[i]) { 12 | break; 13 | } 14 | } 15 | } 16 | 17 | return dp[0]; 18 | } 19 | -------------------------------------------------------------------------------- /typescript/152-Maximum-Product-Subarray.ts: -------------------------------------------------------------------------------- 1 | function maxProduct(nums: number[]): number { 2 | let res = Math.max(...nums); 3 | let curMax = 1; 4 | let curMin = 1; 5 | 6 | for (const n of nums) { 7 | if (n === 0) { 8 | curMin = 1; 9 | curMax = 1; 10 | continue; 11 | } 12 | 13 | let temp = curMax * n; 14 | curMax = Math.max(n * curMax, n * curMin, n); 15 | curMin = Math.min(temp, n * curMin, n); 16 | res = Math.max(res, curMax); 17 | } 18 | 19 | return res; 20 | } 21 | -------------------------------------------------------------------------------- /typescript/153-Find-Minimum-in-Rotated-Sorted-Array.ts: -------------------------------------------------------------------------------- 1 | function findMin(nums: number[]): number { 2 | let left: number = 0; 3 | let right: number = nums.length - 1; 4 | while (right > left) { 5 | let midIdx: number = Math.floor((left + right) / 2); 6 | if (nums[midIdx] > nums[right]) { 7 | left = midIdx + 1; 8 | } else { 9 | right = midIdx; 10 | } 11 | } 12 | return nums[left]; 13 | } 14 | -------------------------------------------------------------------------------- /typescript/167-Two-Sum-II.ts: -------------------------------------------------------------------------------- 1 | function twoSum(numbers: number[], target: number): number[] { 2 | let L = 0; 3 | let R = numbers.length - 1; 4 | 5 | while (numbers[L] + numbers[R] !== target) { 6 | if (numbers[L] + numbers[R] > target) { 7 | R = R - 1; 8 | } else if (numbers[L] + numbers[R] < target) { 9 | L = L + 1; 10 | } 11 | } 12 | 13 | return [L + 1, R + 1]; 14 | } 15 | -------------------------------------------------------------------------------- /typescript/190-Reverse-Bits.ts: -------------------------------------------------------------------------------- 1 | function reverseBits(n: number): number { 2 | let result = 0b0; 3 | 4 | for (let i = 0; i < 32; i++) { 5 | const bit = n & 0b1; 6 | result <<= 1; 7 | result |= bit; 8 | n >>= 1; 9 | } 10 | return result >>> 0; 11 | } 12 | -------------------------------------------------------------------------------- /typescript/191-Number-of-1-Bits.ts: -------------------------------------------------------------------------------- 1 | function hammingWeight(n: number): number { 2 | let base2 = n.toString(2).split(''); 3 | let count = 0; 4 | 5 | base2.forEach((item) => { 6 | if (item === '1') { 7 | count += 1; 8 | } 9 | }); 10 | 11 | return count; 12 | } 13 | -------------------------------------------------------------------------------- /typescript/198-House-Robber.ts: -------------------------------------------------------------------------------- 1 | function rob(nums: number[]): number { 2 | let rob1 = 0; 3 | let rob2 = 0; 4 | 5 | for (const n of nums) { 6 | let temp = Math.max(n + rob1, rob2); 7 | rob1 = rob2; 8 | rob2 = temp; 9 | } 10 | 11 | return rob2; 12 | } 13 | -------------------------------------------------------------------------------- /typescript/202-Happy-Number.ts: -------------------------------------------------------------------------------- 1 | function isHappy(n: number): boolean { 2 | const visit = new Set(); 3 | 4 | while (!visit.has(n)) { 5 | visit.add(n); 6 | n = sumOfSquares(n); 7 | 8 | if (n == 1) return true; 9 | } 10 | 11 | return false; 12 | } 13 | 14 | function sumOfSquares(n: number): number { 15 | let output = 0; 16 | 17 | while (n) { 18 | let digit = n % 10; 19 | digit = digit ** 2; 20 | output += digit; 21 | n = Math.floor(n / 10); 22 | } 23 | 24 | return output; 25 | } 26 | -------------------------------------------------------------------------------- /typescript/213-House-Robber-II.ts: -------------------------------------------------------------------------------- 1 | function helper(nums: number[]): number { 2 | let rob1 = 0; 3 | let rob2 = 0; 4 | 5 | for (const n of nums) { 6 | let temp = Math.max(n + rob1, rob2); 7 | rob1 = rob2; 8 | rob2 = temp; 9 | } 10 | 11 | return rob2; 12 | } 13 | 14 | function rob(nums: number[]): number { 15 | return Math.max( 16 | nums[0], 17 | helper(nums.slice(0, nums.length - 1)), 18 | helper(nums.slice(1)) 19 | ); 20 | } 21 | -------------------------------------------------------------------------------- /typescript/217-Contains-Duplicate.ts: -------------------------------------------------------------------------------- 1 | function containsDuplicate(nums: number[]): boolean { 2 | const set = new Set(); 3 | 4 | for (let i = 0; i < nums.length; i++) { 5 | if (set.has(nums[i])) return true; 6 | else set.add(nums[i]); 7 | } 8 | 9 | return false; 10 | } 11 | -------------------------------------------------------------------------------- /typescript/230-Kth-Smallest-Element-In-A-BST.ts: -------------------------------------------------------------------------------- 1 | let inDepth = (node, stack) => { 2 | if (node === null) return; 3 | 4 | inDepth(node.left, stack); 5 | 6 | stack.push(node.val); 7 | 8 | inDepth(node.right, stack); 9 | }; 10 | 11 | function kthSmallest(root: TreeNode | null, k: number): number { 12 | let stack = []; 13 | 14 | inDepth(root, stack); 15 | 16 | return stack[k - 1]; 17 | } 18 | -------------------------------------------------------------------------------- /typescript/238-Product-of-Array-Except-Self.ts: -------------------------------------------------------------------------------- 1 | function productExceptSelf(nums: number[]): number[] { 2 | const array: Array = []; 3 | let product: number = 1; 4 | 5 | for (let idx = 0; idx < nums.length; idx++) { 6 | array[idx] = product; 7 | product *= nums[idx]; 8 | } 9 | 10 | product = 1; 11 | 12 | for (let idx = nums.length - 1; idx >= 0; idx--) { 13 | array[idx] *= product; 14 | product *= nums[idx]; 15 | } 16 | 17 | return array; 18 | } 19 | -------------------------------------------------------------------------------- /typescript/242-Valid-Anagram.ts: -------------------------------------------------------------------------------- 1 | function isAnagram(s: string, t: string) { 2 | if (s.length !== t.length) return false; 3 | 4 | let first: Array = s.split(''); 5 | const second = t.split(''); 6 | 7 | for (let i = 0; i < second.length; i++) { 8 | const element = second[i]; 9 | 10 | let found = first.indexOf(element); 11 | 12 | if (found !== -1) { 13 | first[found] = null; 14 | } else { 15 | return false; 16 | } 17 | } 18 | 19 | return true; 20 | } 21 | -------------------------------------------------------------------------------- /typescript/242-Valid-Anagrams.ts: -------------------------------------------------------------------------------- 1 | function isAnagram(s: string, t: string): boolean { 2 | if (s.length !== t.length) return false; 3 | 4 | const store = new Array(26).fill(0); 5 | 6 | for (let i = 0; i < s.length; i++) { 7 | store[s.charCodeAt(i) - 'a'.charCodeAt(0)]++; 8 | store[t.charCodeAt(i) - 'a'.charCodeAt(0)]--; 9 | } 10 | 11 | for (let i = 0; i < store.length; i++) { 12 | if (store[i] !== 0) return false; 13 | } 14 | 15 | return true; 16 | } 17 | -------------------------------------------------------------------------------- /typescript/268-Missing-Number.ts: -------------------------------------------------------------------------------- 1 | function missingNumber(nums: number[]): number { 2 | let sum: number = 0; 3 | let total: number = (nums.length * (nums.length + 1)) / 2; 4 | for (let i = 0; i < nums.length; i++) { 5 | sum += nums[i]; 6 | } 7 | return total - sum; 8 | } 9 | -------------------------------------------------------------------------------- /typescript/3-Longest-Substring-Without-Repeating-Characters.ts: -------------------------------------------------------------------------------- 1 | function lengthOfLongestSubstring(s: string): number { 2 | const charSet = new Set(); 3 | let l = 0; 4 | let res = 0; 5 | 6 | for (let r = 0; r < s.length; r++) { 7 | while (charSet.has(s[r])) { 8 | charSet.delete(s[l]); 9 | l += 1; 10 | } 11 | charSet.add(s[r]); 12 | res = Math.max(res, r - l + 1); 13 | } 14 | return res; 15 | } 16 | -------------------------------------------------------------------------------- /typescript/300-Longest-Increasing-Subsequence.ts: -------------------------------------------------------------------------------- 1 | function lengthOfLIS(nums: number[]): number { 2 | const lis = Array(nums.length).fill(1); 3 | 4 | for (let i = nums.length - 1; i > -1; i--) { 5 | for (let j = i + 1; j < nums.length; j++) { 6 | if (nums[i] < nums[j]) { 7 | lis[i] = Math.max(lis[i], 1 + lis[j]); 8 | } 9 | } 10 | } 11 | 12 | return Math.max(...lis); 13 | } 14 | -------------------------------------------------------------------------------- /typescript/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.ts: -------------------------------------------------------------------------------- 1 | function maxProfit(prices: number[]): number { 2 | let [ sold, hold, rest ] = [ 0, Number.MIN_SAFE_INTEGER, 0]; 3 | 4 | for (let i = 0; i < prices.length; i++) { 5 | let prevSold = sold; 6 | sold = hold + prices[i]; 7 | hold = Math.max(hold, rest - prices[i]); 8 | rest = Math.max(rest, prevSold); 9 | } 10 | return Math.max(sold, rest); 11 | }; -------------------------------------------------------------------------------- /typescript/322-Coin-Change.ts: -------------------------------------------------------------------------------- 1 | function coinChange(coins: number[], amount: number): number { 2 | const dp = Array(amount + 1).fill(amount + 1); 3 | 4 | dp[0] = 0; 5 | 6 | for (let a = 1; a < amount + 1; a++) { 7 | for (const c of coins) { 8 | if (a - c >= 0) { 9 | dp[a] = Math.min(dp[a], 1 + dp[a - c]); 10 | } 11 | } 12 | } 13 | 14 | return dp[amount] != amount + 1 ? dp[amount] : -1; 15 | } 16 | -------------------------------------------------------------------------------- /typescript/338-Counting-Bits.ts: -------------------------------------------------------------------------------- 1 | function countBits(n: number): number[] { 2 | const ans: number[] = []; 3 | 4 | for (let i = 0; i < n + 1; i++) { 5 | ans.push(hammingWeight(i)); 6 | } 7 | 8 | return ans; 9 | } 10 | 11 | function hammingWeight(n: number): number { 12 | let base2 = n.toString(2).split(''); 13 | let count = 0; 14 | 15 | base2.forEach((item) => { 16 | if (item === '1') { 17 | count += 1; 18 | } 19 | }); 20 | 21 | return count; 22 | } 23 | -------------------------------------------------------------------------------- /typescript/371-Sum-Of-Two-Integers.ts: -------------------------------------------------------------------------------- 1 | function getSum(a: number, b: number): number { 2 | let res = a; 3 | let secondInt = b; 4 | 5 | while (secondInt != 0) { 6 | let temp = (res & secondInt) << 1; 7 | res ^= secondInt; 8 | secondInt = temp; 9 | } 10 | return res; 11 | } 12 | -------------------------------------------------------------------------------- /typescript/45-Jump-Game-II.ts: -------------------------------------------------------------------------------- 1 | function jump(nums: number[]): number { 2 | let left = 0; 3 | let right = 0; 4 | let res = 0; 5 | 6 | while (right < nums.length - 1) { 7 | let maxJump = 0; 8 | for (let i = left; i <= right; i++) { 9 | maxJump = Math.max(maxJump, i + nums[i]); 10 | } 11 | left = right + 1; 12 | right = maxJump; 13 | res += 1; 14 | } 15 | return res; 16 | } 17 | -------------------------------------------------------------------------------- /typescript/46-Permutations.ts: -------------------------------------------------------------------------------- 1 | function permute(nums: number[]): number[][] { 2 | const res: number[][] = []; 3 | 4 | if (nums.length === 1) { 5 | return [nums.slice()]; 6 | } 7 | 8 | for (const i of nums) { 9 | let n = nums.shift()!; 10 | 11 | let perms = permute(nums); 12 | 13 | for (const perm of perms) { 14 | perm.push(n); 15 | } 16 | 17 | perms.forEach((perm) => { 18 | res.push(perm); 19 | }); 20 | 21 | nums.push(n); 22 | } 23 | 24 | return res; 25 | } 26 | -------------------------------------------------------------------------------- /typescript/50-Pow.ts: -------------------------------------------------------------------------------- 1 | function myPow(x: number, n: number): number { 2 | function helper(x: number, n: number): number { 3 | if (x == 0) return 0; 4 | if (n == 0) return 1; 5 | 6 | let res = helper(x * x, Math.floor(n / 2)); 7 | return n % 2 ? x * res : res; 8 | } 9 | 10 | let res = helper(x, Math.abs(n)); 11 | return n >= 0 ? res : 1 / res; 12 | } 13 | -------------------------------------------------------------------------------- /typescript/518-Coin-Change-II.ts: -------------------------------------------------------------------------------- 1 | function change(amount: number, coins: number[]): number { 2 | let table = Array(amount + 1).fill(0); 3 | table[0] = 1; 4 | for (let coin of coins) { 5 | for (let i = 0; i < table.length; i++) { 6 | if (coin <= i) { 7 | table[i] += table[i - coin]; 8 | } 9 | } 10 | } 11 | return table[amount]; 12 | } 13 | -------------------------------------------------------------------------------- /typescript/53-Maximum-Subarray.ts: -------------------------------------------------------------------------------- 1 | function maxSubArray(nums: number[]): number { 2 | let maxSub = nums[0]; 3 | let curSum = 0; 4 | 5 | for (const n of nums) { 6 | if (curSum < 0) { 7 | curSum = 0; 8 | } 9 | curSum += n; 10 | maxSub = Math.max(maxSub, curSum); 11 | } 12 | 13 | return maxSub; 14 | } 15 | -------------------------------------------------------------------------------- /typescript/55-Jump-Game.ts: -------------------------------------------------------------------------------- 1 | function canJump(nums: number[]): boolean { 2 | let goal = nums.length - 1; 3 | 4 | for (let i = nums.length - 2; i >= 0; i--) { 5 | if (i + nums[i] >= goal) { 6 | goal = i; 7 | } 8 | } 9 | return goal == 0; 10 | } 11 | -------------------------------------------------------------------------------- /typescript/62-Unique-Paths.ts: -------------------------------------------------------------------------------- 1 | function uniquePaths(m: number, n: number): number { 2 | let row = new Array(n).fill(1); 3 | 4 | for (let i = 0; i < m - 1; i++) { 5 | let newRow = new Array(n).fill(1); 6 | 7 | for (let j = n - 2; j > -1; j--) { 8 | newRow[j] = newRow[j + 1] + row[j]; 9 | } 10 | 11 | row = newRow; 12 | } 13 | 14 | return row[0]; 15 | } 16 | -------------------------------------------------------------------------------- /typescript/66-Plus-One.ts: -------------------------------------------------------------------------------- 1 | function plusOne(digits: number[]): number[] { 2 | return (BigInt(digits.join('')) + BigInt(1)) 3 | .toString() 4 | .split('') 5 | .map((item) => Number(item)); 6 | } 7 | -------------------------------------------------------------------------------- /typescript/70-Climbing-Stairs.ts: -------------------------------------------------------------------------------- 1 | function climbStairs(n: number): number { 2 | let one = 1; 3 | let two = 1; 4 | 5 | for (let i = 0; i < n - 1; i++) { 6 | let temp = one; 7 | one = one + two; 8 | two = temp; 9 | } 10 | return one; 11 | } 12 | -------------------------------------------------------------------------------- /typescript/704-Binary-Search.ts: -------------------------------------------------------------------------------- 1 | function search(nums: number[], target: number): number { 2 | let l = 0, 3 | r = nums.length - 1; 4 | 5 | while (l <= r) { 6 | var m = Math.round((l + r) / 2); 7 | if (nums[m] > target) { 8 | r = m - 1; 9 | } else if (nums[m] < target) { 10 | l = m + 1; 11 | } else { 12 | return m; 13 | } 14 | } 15 | 16 | return -1; 17 | } 18 | -------------------------------------------------------------------------------- /typescript/739-Daily-Temperatures.ts: -------------------------------------------------------------------------------- 1 | function dailyTemperatures(temperatures: number[]): number[] { 2 | let stack = []; 3 | 4 | let result = new Array(temperatures.length).fill(0); 5 | 6 | for (let i = 0; i < temperatures.length; i++) { 7 | let currTemp = temperatures[i]; 8 | 9 | while (stack.length > 0 && currTemp > stack[stack.length - 1].temp) { 10 | let { ind } = stack.pop(); 11 | result[ind] = i - ind; 12 | } 13 | 14 | stack.push({ temp: currTemp, ind: i }); 15 | } 16 | 17 | return result; 18 | } 19 | -------------------------------------------------------------------------------- /typescript/746-Min-Cost-Climbing-Stairs.ts: -------------------------------------------------------------------------------- 1 | function minCostClimbingStairs(cost: number[]): number { 2 | cost.push(0); 3 | 4 | for (let i = cost.length - 3; i > -1; i--) { 5 | cost[i] += Math.min(cost[i + 1], cost[i + 2]); 6 | } 7 | 8 | return Math.min(cost[0], cost[1]); 9 | } 10 | -------------------------------------------------------------------------------- /typescript/78-Subsets.ts: -------------------------------------------------------------------------------- 1 | function subsets(nums: number[]): number[][] { 2 | let res: number[][] = []; 3 | let subset: number[] = []; 4 | function dfs(i: number) { 5 | if (i >= nums.length) { 6 | res.push(subset.slice()); 7 | return; 8 | } 9 | 10 | subset.push(nums[i]); 11 | dfs(i + 1); 12 | 13 | subset.pop(); 14 | dfs(i + 1); 15 | } 16 | 17 | dfs(0); 18 | 19 | return res; 20 | } 21 | -------------------------------------------------------------------------------- /typescript/875-Koko-Eating-Bananas.ts: -------------------------------------------------------------------------------- 1 | function minEatingSpeed(piles: number[], h: number): number { 2 | let l = 1; 3 | let r = Math.max(...piles); 4 | let res = r; 5 | 6 | while (l <= r) { 7 | let k = Math.floor((l + r) / 2); 8 | let hours = 0; 9 | for (const p of piles) { 10 | hours += Math.ceil(p / k); 11 | } 12 | if (hours <= h) { 13 | res = Math.min(res, k); 14 | r = k - 1; 15 | } else { 16 | l = k + 1; 17 | } 18 | } 19 | 20 | return res; 21 | } 22 | -------------------------------------------------------------------------------- /typescript/9-Palindrome-Number.ts: -------------------------------------------------------------------------------- 1 | var isPalindrome = (x: number) => { 2 | // Creates array from int characters 3 | // 121 -> [1,2,1] 4 | let arr = Array.from(String(x), Number); 5 | 6 | // Uses two pointer 7 | for (let i = 0; i < arr.length; i++) { 8 | if (arr[i] !== arr[arr.length - 1 - i]) { 9 | return false; 10 | } 11 | } 12 | return true; 13 | }; 14 | -------------------------------------------------------------------------------- /typescript/91-Decode-Ways.ts: -------------------------------------------------------------------------------- 1 | function numDecodings(s: string): number { 2 | let dp = { 3 | [s.length]: 1, 4 | }; 5 | 6 | for (let i = s.length - 1; i > -1; i--) { 7 | if (s[i] == '0') { 8 | dp[i] = 0; 9 | } else { 10 | dp[i] = dp[i + 1]; 11 | } 12 | if ( 13 | i + 1 < s.length && 14 | (s[i] == '1' || (s[i] == '2' && '0123456'.includes(s[i + 1]))) 15 | ) { 16 | dp[i] += dp[i + 2]; 17 | } 18 | } 19 | return dp[0]; 20 | } 21 | --------------------------------------------------------------------------------