From 6dfca929ef9d56b431e9149c7e8b977cfdf638f3 Mon Sep 17 00:00:00 2001 From: Bot-A0 <71089234+Ahmad-A0@users.noreply.github.com> Date: Thu, 21 Jul 2022 11:47:24 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20Format=20files=20(=F0=9F=9B=A0?= =?UTF-8?q?=EF=B8=8F=20from=20Github=20Actions)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- java/1-Two-Sum.java | 33 +- java/100-Same-Tree.java | 38 +- ...102-Binary-Tree-Level-Order-Traversal.java | 45 +-- java/104-Maximum-Depth-of-Binary-Tree.java | 9 +- java/1046-Last-Stone-Weight.java | 21 +- ...e-from-Preorder-and-Inorder-Traversal.java | 83 ++-- ...-from-Inorder-and-Postorder-Traversal.java | 70 +++- ...-Binary-Tree-Level-Order-Traversal-II.java | 43 ++- java/11-Container-With-Most-Water.java | 33 +- java/110-Balanced-Binary-Tree.java | 36 +- java/1143-Longest-Common-Subsequence.java | 29 +- ...-Number-of-Dice-Rolls-With-Target-Sum.java | 42 +- ...ords-That-Can-Be-Formed-by-Characters.java | 38 +- java/119-Pascal's-Triangle-II.java | 35 +- java/121-Best-Time-to-Buy-and-Sell-Stock.java | 17 +- java/124-Binary-Tree-Maximum-Path-Sum.java | 49 ++- ...275-Find-Winner-on-a-Tic-Tac-Toe-Game.java | 58 ++- java/128-Longest-Consecutive-Sequence.java | 31 +- java/128. Longest Consecutive Sequence.java | 62 +-- java/130-Surrounded-Regions.java | 71 ++-- java/131-Palindrome-Partitioning.java | 44 +-- java/133-Clone-Graph.java | 26 +- java/134-Gas-Station.java | 31 +- java/136-Single-Number.java | 12 +- java/138-Copy-List-with-Random-Pointer.java | 29 +- java/139-Word- Break.java | 43 ++- java/141. Linked List Cycle.java | 19 +- java/143-Reorder-List.java | 55 +-- .../1448-Count-Good-Nodes-in-Binary-Tree.java | 33 +- java/146-LRU-Cache.java | 156 ++++---- java/15-3Sum.java | 65 ++-- .../150-Evaluate-Reverse-Polish-Notation.java | 41 +- java/152-Maximum-Product-Subarray.java | 29 +- ...-Find-Minimum-in-Rotated-Sorted-Array.java | 35 +- java/155-Min-Stack.java | 63 ++- java/167-Two-Sum-II.java | 42 +- ...Letter-Combinations-of-a-Phone-Number.java | 78 ++-- java/187-Repeated-DNA-Sequences.java | 26 +- java/19-Remove-Nth-Node-From-End-of-List.java | 34 +- java/190-Reverse-Bits.java | 29 +- java/191-Number-of-1-Bits.java | 40 +- java/198-House-Robber.java | 58 +-- java/199-Binary-Tree-Right-Side-View.java | 40 +- java/2-Add-Two-Numbers.java | 104 ++--- java/20-Valid-Parentheses.java | 37 +- java/200-Number-of-Islands.java | 47 ++- java/202-Happy-Number.java | 53 ++- java/206. Reverse Linked List.java | 46 +-- java/207-Course-Schedule.java | 67 ++-- java/208-Implement-Trie-Prefix-Tree.java | 88 ++--- java/21-Merge-Two-Sorted-Lists.java | 60 +-- java/210-Course-Schedule-II.java | 76 ++-- java/213-House-RobberII.java | 39 +- java/215-Kth-Largest-Element-in-an-Array.java | 33 +- java/217-Contains-Duplicate.java | 19 +- java/22-Generate-Parentheses.java | 64 ++-- java/226-Invert-Binary-Tree.java | 17 +- java/23-Merge-k-Sorted-Lists.java | 42 +- java/230-Kth-Smallest-Element-in-a-BST.java | 27 +- ...nglish-Letter-in-Upper-and-Lower-Case.java | 20 +- ...310-Sum-of-Numbers-With-Units-Digit-K.java | 30 +- ...-Number-of-Increasing-Paths-in-a-Grid.java | 68 ++-- java/234. Palindrome Linked List.java | 55 ++- ...mmon-Ancestor-of-a-Binary-Search-Tree.java | 19 +- ...west-Common-Ancestor-of-a-Binary-Tree.java | 23 +- java/238-Product-of-Array-Except-Self.java | 35 +- java/239-Sliding-Window-Maximum.java | 26 +- java/24 Swap Nodes in Pairs.java | 46 +-- java/242-Valid-Anagram.java | 25 +- java/25-Reverse-Nodes-in-k-Group.java | 39 +- java/252-Meeting-Rooms.java | 45 +-- java/253-Meeting-Rooms-ii.java | 38 +- java/261-Graph-Valid-Tree.java | 55 +-- java/268-Missing-Number.java | 15 +- java/27-Remove-Element.java | 37 +- java/271-Encode-and-Decode-Strings.java | 38 +- java/279-Perfect-Squares.java | 43 ++- java/286-Walls-and-Gates.java | 62 +-- java/287-Find-the-Duplicate-Number.java | 37 +- java/295-Find-Median-from-Data-Stream.java | 54 +-- ...Serialize-and-Deserialize-Binary-Tree.java | 71 ++-- ...ubstring-Without-Repeating-Characters.java | 27 +- java/300-Longest-Increasing-Subsequence.java | 35 +- ...e-To-Buy-and-Sell-Stock-With-Cooldown.java | 52 +-- java/322-Coin-Change.java | 33 +- ...ted-Components-in-an-Undirected-Graph.java | 91 ++--- ...9-Longest-Increasing-Path-in-a-Matrix.java | 66 ++-- java/33-Search-In-Rotated-Sorted-Array.java | 85 +++-- java/338-Counting-Bits.java | 32 +- java/347-Top-K-Frequent-Elements.java | 139 +++---- java/36-valid-sudoku.java | 59 +-- java/37-Sudoku-Solver.java | 92 ++--- java/371-Sum-of-Two-Integers.java | 15 +- java/39-Combination-Sum.java | 49 +-- java/4-Median-of-Two-Sorted-Arrays.java | 91 ++--- java/40-Combination-Sum-II.java | 48 +-- java/416-Partition-Equal-Subset-Sum.java | 46 ++- java/417-Pacific-Atlantic-Water-Flow.java | 70 ++-- java/42-Trapping-Rain-Water.java | 39 +- ...ngest-Repeating-Character-Replacement.java | 31 +- java/435-Non-Overlapping-Intervals.java | 48 +-- ...d-All-Numbers-Disappeared-in-an-Array.java | 32 +- java/45-Jump-game-II.java | 24 +- java/46-Permutations.java | 52 +-- java/48-Rotate-Image.java | 43 ++- java/49-Group-Anagrams.java | 31 +- java/494-Target-Sum.java | 27 +- java/5-Longest-Palindromic-Substring.java | 69 ++-- java/50-Pow(x, n).java | 49 +-- java/51-N-Queens.java | 102 ++--- java/53-Maximum-Subarray.java | 31 +- java/54-Spiral-Matrix.java | 67 ++-- java/543-Diameter-of-Binary-Tree.java | 27 +- java/55-Jump-Game.java | 18 +- java/56-Merge-Intervals.java | 38 +- java/567-Permutation-in-String.java | 60 +-- java/57-Insert-Interval.java | 33 +- java/572-Subtree-of-Another-Tree.java | 20 +- java/6-Zigzag-Conversion.java | 51 +-- java/60-Permutation-Sequence.java | 151 ++++---- java/617-Merge-Two-Binary-Trees.java | 40 +- java/62-Unique-Paths.java | 43 ++- java/621-Task-Scheduler.java | 48 ++- java/63-Unique-Paths-II.java | 41 +- .../637-Average-of-Levels-in-Binary-Tree.java | 35 +- java/64-Minimum-Path-Sum.java | 48 +-- java/647-Palindromic-Substrings.java | 52 +-- java/66-Plus-One.java | 50 +-- java/662-Maximum-Width-of-Binary-Tree.java | 37 +- java/695-Max-Area-of-Island.java | 47 ++- java/7-Reverse-Integer.java | 41 +- java/70-Climbing-Stairs.java | 79 ++-- java/703-Kth-Largest-Element-in-a-Stream.java | 29 +- java/704-Binary-Search.java | 27 +- java/713-Subarray-Product-Less-Than-K.java | 23 +- java/72-Edit-Distance.java | 70 ++-- java/73-Set-Matrix-Zeroes.java | 71 ++-- java/739-Daily-Temperatures.java | 25 +- java/74-Search-A-2D-Matrix.java | 33 +- java/746-Min-Cost-Climbing-Stairs.java | 22 +- java/75-Sort-Colors.java | 35 +- java/752-Open-the-lock.java | 82 ++-- java/76-Minimum-Window-Substring.java | 57 +-- java/763-Partition-Labels.java | 40 +- java/767-Reorganize-String.java | 71 ++-- java/779-K-th-Symbol-in-Grammar.java | 19 +- java/78-Subsets.java | 42 +- java/79-Word-Search.java | 64 ++-- java/797-All-Paths-From-Source-to-Target.java | 41 +- ...3. Remove Duplicates from Sorted List.java | 31 +- java/84-Largest-Rectangle-in-Histogram.java | 69 ++-- java/852. Peak Index in a Mountain Array.java | 30 +- java/853-Car Fleet.java | 43 +-- ...3-All-Nodes-Distance-K-in-Binary-Tree.java | 86 ++--- java/875-Koko-Eating-Bananas.java | 53 +-- java/876. Middle of the Linked List.java | 17 +- java/90-Subsets-II.java | 47 ++- java/97-Interleaving-String.java | 39 +- java/973-K-Closest-Points-to-Origin.java | 76 ++-- java/98-Validate-Binary-Search-Tree.java | 23 +- java/981-Time-Based-Key-Value-Store.java | 52 +-- java/986-Interval-List-Intersections.java | 9 +- java/994-Rotting-Oranges.java | 64 ++-- javascript/1-Two-Sum.js | 16 +- javascript/100-Same-Tree.js | 8 +- .../102-Binary-Tree-Level-Order-Traversal.js | 35 +- .../104-Maximum-Depth-of-Binary-Tree.js | 18 +- javascript/1046-Last-Stone-Weight.js | 129 +++---- ...ree-from-Preorder-and-Inorder-Traversal.js | 20 +- javascript/11-Container-With-Most-Water.js | 28 +- javascript/110-Balanced-Binary-Tree.js | 23 +- javascript/1143-Longest-Common-Subsequence.js | 2 +- javascript/115-Distinct-Subsequences.js | 145 ++++--- .../121-Best-Time-to-Buy-and-Sell-Stock.js | 20 +- .../124-Binary-Tree-Maximum-Path-Sum.js | 70 ++-- javascript/125-Valid-Palindrome.js | 33 +- javascript/127-Word-Ladder.js | 4 +- .../128-Longest-consecutive-sequence.js | 101 +++-- javascript/13-Roman-to-Integer.js | 102 ++--- javascript/130-Surrounded-Regions.js | 104 +++-- javascript/131-Palindrome-Partitioning.js | 66 ++-- javascript/133-Clone-Graph.js | 48 +-- javascript/136-Single-Number.js | 10 +- .../138-Copy-List-with-Random-Pointer.js | 2 +- javascript/139-Word-Break.js | 28 +- javascript/141-Linked-List-Cycle.js | 22 +- javascript/143-Reorder-List.js | 75 ++-- .../1448-Count-Good-Nodes-in-Binary-Tree.js | 40 +- javascript/146-LRU-Cache.js | 197 +++++----- javascript/15-3Sum.js | 64 ++-- .../150-Evaluate-Reverse-Polish-Notation.js | 28 +- javascript/152-Maximum-Product-Subarray.js | 27 +- ...53-Find-Minimum-in-Rotated-Sorted-Array.js | 22 +- javascript/155-Min-Stack.js | 75 ++-- .../160-Intersection-of-Two-Linked-Lists.js | 18 +- javascript/167-Two-Sum-II.js | 20 +- ...7-Letter-Combinations-of-a-Phone-Number.js | 62 +-- .../19-Remove-Nth-Node-From-End-of-List.js | 39 +- javascript/190-Reverse-Bits.js | 20 +- javascript/191-Number-of-1-bits.js | 12 +- javascript/198-House-Robber.js | 24 +- javascript/199-binary-tree-right-side-view.js | 44 +-- javascript/2-Add-Two-Numbers.js | 54 +-- javascript/20-Valid-Parentheses.js | 51 ++- javascript/200-Number-of-Islands.js | 14 +- javascript/202-Happy-Number.js | 50 +-- javascript/206-Reverse-Linked-List.js | 22 +- javascript/207-canFinish.js | 2 +- javascript/208-Implement-Trie.js | 68 ++-- javascript/21-Merge-Two-Sorted-Lists.js | 28 +- javascript/210-Course-Schedule-II.js | 32 +- ...ign-Add-and-Search-Words-Data-Structure.js | 76 ++-- javascript/212-Word-Search-ii.js | 153 ++++---- javascript/213-House-Robber-II.js | 30 +- javascript/217-Contains-Duplicate.js | 34 +- javascript/22-Generate-Parentheses.js | 66 ++-- javascript/226-Invert-Binary-Tree.js | 13 +- javascript/23-Merge-K-Sorted-Lists.js | 5 +- .../230-Kth-Smallest-Element-in-a-BST.js | 42 +- javascript/234-Palindrome-Linked-List.js | 60 +-- ...common-ancestor-of-a-binary-search-tree.js | 20 +- .../238-Product-of-Array-Except-Self.js | 33 +- javascript/239-Sliding-Window-Maximum.js | 39 +- javascript/242-Valid-Anagram.js | 42 +- javascript/25-Reverse-Nodes-in-K-Group.js | 102 ++--- javascript/268-Missing-Number.js | 20 +- javascript/269-Alien-Dictionary.js | 82 ++-- javascript/271-Encode-and-Decode-Strings.js | 27 +- javascript/286-Walls-And-Gates.js | 122 +++--- javascript/287-Find-the-Duplicate-Number.js | 48 +-- ...7-Serialize-and-Deserialize-Binary-Tree.js | 124 +++--- ...-Substring-Without-Repeating-Characters.js | 2 +- .../300-Longest-Increasing-Subsequence.js | 20 +- javascript/322-Coin-Change.js | 20 +- javascript/323-countComponents.js | 2 +- .../33-Search-in-Rotated-Sorted-Array.js | 17 +- javascript/332-Reconstruct-Itinerary.js | 58 +-- javascript/338-Counting-Bits.js | 10 +- javascript/347-Top-K-Frequent-Elements.js | 45 ++- javascript/347-Top-K-Frquent-Elements.js | 45 ++- javascript/35-Search-Insert-Position.js | 30 +- javascript/36-Valid-Sudoku.js | 54 +-- javascript/371-Sum-of-Two-Integers.js | 18 +- javascript/39-Combination-Sum.js | 54 ++- javascript/4-Median-Of-Two-Sorted-Arrays.js | 58 ++- javascript/40-Combination-Sum-II.js | 70 ++-- javascript/417-Pacific-Atlantic-Water-Flow.js | 139 ++++--- javascript/42-Trapping-Rain-Water.js | 156 ++++---- ...Longest-Repeating-Character-Replacement.js | 49 ++- javascript/435-Non-overlapping-Intervals.js | 24 +- javascript/46-Permutations.js | 50 +-- javascript/473-Matchsticks-To-Square.js | 74 ++-- javascript/49-Group-Anagrams.js | 68 ++-- javascript/49-Rotate-Image.js | 42 +- javascript/5-Longest-Palindromic-Substring.js | 68 ++-- javascript/50. Pow(x, n).js | 30 +- javascript/51-solveNQueens.js | 8 +- javascript/52-totalNQueens.js | 2 +- javascript/53-Maximum-Subarray.js | 18 +- javascript/54-Spiral-Matrix.js | 62 +-- javascript/543-Diameter-Of-Binary-Tree.js | 30 +- javascript/55-Jump-Game.js | 22 +- javascript/56-Merge-Intervals.js | 2 +- javascript/567-Permutation-In-String.js | 225 ++++++----- javascript/57-Insert-Interval.js | 42 +- javascript/572-Subtree-of-Another-Tree.js | 36 +- javascript/62-Unique-Paths.js | 30 +- javascript/647-Palindromic-Substrings.js | 50 +-- javascript/66-plus-one.js | 22 +- javascript/695-Max-Area-Of-Island.js | 58 +-- javascript/70-Climbing-Stairs.js | 28 +- .../703-Kth-Largest-Element-In-A-Stream.js | 230 +++++------ javascript/704-Binary-Search.js | 27 +- javascript/72-Edit-Distance.js | 54 ++- javascript/73-Set-Matrix-Zeroes.js | 37 +- javascript/739-daily-temperatures.js | 26 +- javascript/74-Search-A-2D-Matrix.js | 116 +++--- javascript/746-Min-Cost-Climbing-Stairs.js | 18 +- javascript/76-Minimum-Window-Substring.js | 8 +- javascript/78-Subsets.js | 40 +- javascript/79-Word-Search.js | 17 +- .../84-Largest-Rectangle-in-Histogram.js | 44 +-- javascript/853-Car-Fleet.js | 50 +-- javascript/875-Koko-Eating-Bananas.js | 41 +- javascript/9-Palindrome-Number.js | 21 +- javascript/90-Subsets-II.js | 44 +-- javascript/91-Decode-Ways.js | 40 +- javascript/97-Interleaving-String.js | 180 ++++----- javascript/973-K-Closest-Points-to-Origin.js | 358 +++++++++--------- javascript/98-Validate-Binary-Search-Tree.js | 22 +- javascript/981-Time-Based-Key-Value-Store.js | 53 ++- javascript/994-Rotting-Oranges.js | 58 +-- python/1-Two-Sum.py | 4 +- python/10-Regular-Expression-Matching.py | 31 +- python/100-Same-Tree.py | 9 +- .../102-Binary-Tree-Level-Order-Traversal.py | 14 +- python/104-Maximum-Depth-of-Binary-Tree.py | 14 +- python/1046-Last-Stone-Weight.py | 4 +- ...ree-from-Preorder-and-Inorder-Traversal.py | 6 +- python/11-Container-With-Most-Water.py | 2 +- python/110-Balanced-Binary-Tree.py | 10 +- python/1143-Longest-Common-Subsequence.py | 4 +- python/115-Distinct-Subsequences.py | 10 +- python/12-Integer-To-Roman.py | 21 +- ...ve-All-Adjacent-Duplicates-in-String-II.py | 12 +- python/121-Best-Time-To-Buy-and-Sell-Stock.py | 2 +- ...catenated-String-with-Unique-Characters.py | 8 +- python/124-Binary-Tree-Maximum-Path-Sum.py | 8 +- python/125-Valid-Palindrome.py | 16 +- python/127-Word-Ladder.py | 8 +- python/128-Longest-consecutive-sequence.py | 3 +- python/13-Roman-To-Integer.py | 3 +- python/130-Surrounded-Regions.py | 14 +- python/131-Palindrome-Partitioning.py | 7 +- python/133-Clone-Graph.py | 8 +- python/134-Gas-Station.py | 10 +- python/138-Copy-List-With-Random-Pointer.py | 7 +- python/139-Word-Break.py | 6 +- python/141-Linked-List-Cycle.py | 3 +- python/143-Reorder-List.py | 4 +- .../1448-Count-Good-Nodes-in-Binary-Tree.py | 5 +- python/146-LRU-Cache.py | 16 +- python/15-3Sum.py | 4 +- python/152-Maximum-Product-Subarray.py | 6 +- ...53-Find-Minimum-in-Rotated-Sorted-Array.py | 2 +- python/155-Min-Stack.py | 3 +- python/1584-Min-Cost-to-Connect-all-Points.py | 6 +- .../160-Intersection-of-Two-Linked-Lists.py | 7 +- python/167-Two-Sum-II.py | 6 +- ...7-Letter-Combinations-of-a-Phone-Number.py | 24 +- ...-Minimum-Interval-to-Include-Each-Query.py | 2 +- ...9-Merge-Triplets-to-Form-Target-Triplet.py | 2 +- python/19-Remove-Nth-node-from-end-of-List.py | 6 +- python/1905-Count-Sub-Islands.py | 18 +- python/191-Number-of-1-Bits.py | 2 +- python/198-House-Robber.py | 2 +- python/199-Binary-Tree-Right-Side-View.py | 6 +- python/2-Add-Two-Numbers.py | 6 +- python/20-Valid-Parentheses.py | 8 +- python/200-Number-of-Islands.py | 18 +- python/2013-Detect-Squares.py | 6 +- python/202-Happy-Number.py | 4 +- python/206-Reverse-Linked-List.py | 5 +- python/207-Course-Schedule.py | 17 +- python/208-Implement-Trie.py | 13 +- python/21-Merge-Two-Sorted-Lists.py | 6 +- python/210-Course-Schedule-II.py | 11 +- ...ign-Add-and-Search-Words-Data-Structure.py | 9 +- python/212-Word-Search-II.py | 32 +- python/213-House-Robber-II.py | 4 +- python/215-Kth-Largest-Element-in-an-Array.py | 20 +- python/217-Contains-Duplicate.py | 2 +- python/22-Generate-Parentheses.py | 6 +- python/221-Maximal-Square.py | 9 +- python/226-Invert-Binary-Tree.py | 4 +- python/23-Merge-K-Sorted-Lists.py | 6 +- python/230-Kth-Smallest-Element-in-a-BST.py | 3 +- ...Lowest-Common-Ancestor-of-a-Binary-Tree.py | 20 +- python/238-Product-of-array-except-self.py | 3 +- python/239-Sliding-Window-Maximum.py | 4 +- python/24-Swap-Nodes-in-Pairs.py | 8 +- python/242-Valid-Anagrams.py | 4 +- python/25-Reverse-Nodes-in-K-Group.py | 10 +- python/252-Meeting-Rooms.py | 5 +- python/253-Meeting-Rooms-ii.py | 1 + .../26-Remove-Duplicates-from-Sorted Array.py | 3 +- python/261-Graph-Valid-Tree.py | 14 +- python/268-Missing-Number.py | 4 +- python/269-Alien-Dictionary.py | 46 +-- python/27-Remove-Element.py | 4 +- python/271-Encode-and-Decode-Strings.py | 2 + python/28-Implement-strStr.py | 11 +- python/286-Walls-and-Gates.py | 10 +- python/287-Find-The-Duplicate-Number.py | 2 +- python/295-Find-Median-from-Data-Stream.py | 9 +- ...7-Serialize-and-Deserialize-Binary-Tree.py | 10 +- ...-Substring-Without-Repeating-Characters.py | 2 +- python/300-Longest-Increasing-Subsequence.py | 2 +- ...ime-To-Buy-and-Sell-Stock-With-Cooldown.py | 10 +- python/312-Burst-Balloons.py | 2 +- python/322-Coin-Change.py | 4 +- ...ected-Components-in-an-Undirected-Graph.py | 21 +- ...329-Longest-Increasing-Path-in-a-Matrix.py | 10 +- python/33-Search-In-Rotated-Sorted-Array.py | 4 +- python/332-Reconstruct-Itinerary.py | 11 +- python/338-Counting-Bits.py | 2 +- ...ast-Position-of-Element-in-Sorted-Array.py | 4 +- python/347-Top-k-frequent-elements.py | 6 +- python/355-Design-Twitter.py | 7 +- python/36-Valid-Sudoku.py | 14 +- python/371-Sum-of-Two-Integers.py | 14 +- python/377-Combination-Sum-IV.py | 9 +- python/39-Combination-Sum.py | 8 +- python/394-decode-string.py | 8 +- python/4-median-of-two-sorted-arrays.py | 13 +- python/40-Combination-Sum-II.py | 7 +- python/40-Combinations-Sum-ii.py | 6 +- python/410-Split-Array-Largest-Sum.py | 2 +- python/416-Partition-Equal-Subset-Sum.py | 4 +- python/417-Pacific-Atlantic-Waterflow.py | 19 +- python/42-Trapping-Rain-Water.py | 7 +- ...Longest-Repeating-Character-Replacement.py | 6 +- python/43-Multiply-Strings.py | 4 +- ...ected_Components_in_an_Undirected_Graph.py | 6 +- python/435-Non-Overlapping-Intervals.py | 2 +- ...ind-all-Numbers-Disappeared-in-an-Array.py | 2 +- python/45-Jump-Game-II.py | 2 +- python/46-Permutations.py | 8 +- python/463-Island-Perimeter.py | 9 +- python/473-Matchsticks-to-Square.py | 7 +- python/48-Rotate-Image.py | 10 +- python/49-Group-Anagrams.py | 2 +- python/494-Target-Sum.py | 12 +- python/5-Longest-Palindromic-Substring.py | 10 +- python/50-Pow(x, n).py | 10 +- python/51-N-Queens.py | 16 +- python/518-coin-change-2.py | 26 +- python/53-Maximum-Subarray.py | 2 +- python/54-Spiral-Matrix.py | 4 +- python/543-Diameter-of-Binary-Tree.py | 6 +- python/55-Jump-Game.py | 4 +- python/56-Merge-Intervals.py | 8 +- python/567-Permutation-in-String.py | 26 +- python/57-Insert-Interval.py | 11 +- python/572-Subtree-of-Another-Tree.py | 16 +- python/617-Merge-Two-Binary-Trees.py | 4 +- python/62-Unique-Paths.py | 4 +- python/621-Task-Scheduler.py | 10 +- python/647-Palindromic-Substrings.py | 4 +- python/658-Find-K-Closest-Elements.py | 35 +- python/66-Plus-One.py | 2 +- ...umber-of-Longest-Increasing-Subsequence.py | 42 +- python/678-Valid-Parenthesis-String.py | 22 +- python/684-Redundant-Connection.py | 11 +- python/695-Max-Area-of-Island.py | 18 +- python/7-Reverse-Integer.py | 14 +- python/70-Climbing-Stairs.py | 5 +- python/703-Kth-Largest-Element-in-a-Stream.py | 1 - python/704-Binary-Search.py | 4 +- python/72-Edit-Distance.py | 4 +- python/724-Find-Pivot-Index.py | 4 +- python/73-Set-Matrix-Zeroes.py | 8 +- python/739-Daily-Temperatures.py | 6 +- python/74-Search-a-2D-Matrix.py | 4 +- python/743-Network-Delay-Time.py | 6 +- python/746-Min-Cost-Climbing-Stairs.py | 4 +- python/752-Open-the-Lock.py | 14 +- python/76-Minimum-Window-Substring.py | 15 +- python/763-Partition-Labels.py | 4 +- python/767-Reorganize-String.py | 8 +- python/778-Swim-in-Rising-Water.py | 16 +- python/78-Subsets.py | 5 +- python/787-Cheapest-Flights-within-K-stops.py | 10 +- python/79-Word-Search.py | 28 +- python/84-Largest-Rectangle-in-Histogram.py | 6 +- python/846-Hand-of-Straights.py | 6 +- python/853-Car-Fleet.py | 2 +- python/875-Koko-Eating-Bananas.py | 6 +- python/90-Subsets-II.py | 9 +- python/909-Snakes-and-Ladders.py | 5 +- python/91-Decode-ways.py | 18 +- python/92-Reverse-Linked-List-II.py | 14 +- python/94-Binary-Tree-Inorder-Traversal.py | 5 +- python/97-Interleaving-Strings.py | 6 +- python/973-K-Closest-Points-to-Origin.py | 2 +- python/98-Validate-Binary-Search-Tree.py | 10 +- python/981-Time-Based-Key-Value-Store.py | 5 +- python/994-Rotting-Oranges.py | 14 +- ruby/104-Maximum-Depth-of-Binary-Tree.rb | 2 +- ruby/1046-Last-Stone-Weight.rb | 4 +- ruby/155-Min-Stack.rb | 8 +- ruby/20-Valid-Parentheses.rb | 6 +- ruby/200-Number-of-Islands.rb | 6 +- ruby/206-Reverse-Linked-List.rb | 2 +- ruby/208-Implement-Trie.rb | 2 +- ruby/338-Counting-Bits.rb | 8 +- ruby/36-Valid-Sudoku.rb | 2 +- ruby/70-Climbing-Stairs.rb | 1 + ruby/703-Kth-Largest-Element-in-a-Stream.rb | 2 +- ruby/746-Min-Cost-Climbing-Stairs.rb | 2 +- typescript/1-Two-Sum.ts | 8 +- typescript/110-Balanced-Binary-Tree.ts | 3 +- typescript/1143-Longest-Common-Subsequence.ts | 14 +- typescript/125-Valid-Palindrome.ts | 8 +- .../150-Evaluate-Reverse-Polish-Notation.ts | 8 +- ...53-Find-Minimum-in-Rotated-Sorted-Array.ts | 12 +- ...7-Letter-Combinations-of-a-Phone-Number.ts | 18 +- .../19-Remove-Nth-Node-From-End-of-List.ts | 36 +- typescript/191-Number-of-1-Bits.ts | 4 +- typescript/2-Add-Two-Numbers.ts | 28 +- typescript/20-Valid-Parentheses.ts | 8 +- typescript/206-Reverse-Linked-List.ts | 12 +- typescript/208-Implement-Trie.ts | 12 +- typescript/21-Merge-Two-Sorted-Lists.ts | 20 +- ...ign-Add-and-Search-Words-Data-Structure.ts | 2 +- typescript/22-Generate-Parentheses.ts | 6 +- ...Common-Ancestor-of-a-Binary Search-Tree.ts | 6 +- .../238-Product-of-Array-Except-Self.ts | 16 +- typescript/242-Valid-Anagram.ts | 4 +- typescript/261-Graph-Valid-Tree.ts | 30 +- typescript/268-Missing-Number.ts | 8 +- .../33-Search-in-Rotated-Sorted-Array.ts | 18 +- typescript/338-Counting-Bits.ts | 4 +- typescript/36-Valid-Sudoku.ts | 2 +- typescript/43-Multiply-Strings.ts | 22 +- typescript/49-Group-Anagrams.ts | 6 +- typescript/5-Longest-Palindromic-Substring.ts | 2 +- typescript/567-Permutation-in-String.ts | 8 +- typescript/66-Plus-One.ts | 4 +- typescript/7-Reverse-Integer.ts | 46 +-- typescript/9-Palindrome-Number.ts | 26 +- typescript/91-Decode-Ways.ts | 4 +- 512 files changed, 8250 insertions(+), 7926 deletions(-) diff --git a/java/1-Two-Sum.java b/java/1-Two-Sum.java index 2f420c89f..1d4425195 100644 --- a/java/1-Two-Sum.java +++ b/java/1-Two-Sum.java @@ -1,18 +1,19 @@ class Solution { - public int[] twoSum(int[] nums, int target) { - HashMap prevMap = new HashMap<>(); - - for (int i = 0; i < nums.length; i++) { - int num = nums[i]; - int diff = target - num; - - if (prevMap.containsKey(nums[i])) { - return new int[]{prevMap.get(num), i}; - } - - prevMap.put(target - num, i); - } - - return new int[]{}; + + public int[] twoSum(int[] nums, int target) { + HashMap prevMap = new HashMap<>(); + + for (int i = 0; i < nums.length; i++) { + int num = nums[i]; + int diff = target - num; + + if (prevMap.containsKey(nums[i])) { + return new int[] { prevMap.get(num), i }; + } + + prevMap.put(target - num, i); } -} \ No newline at end of file + + return new int[] {}; + } +} diff --git a/java/100-Same-Tree.java b/java/100-Same-Tree.java index 851486e05..135287910 100644 --- a/java/100-Same-Tree.java +++ b/java/100-Same-Tree.java @@ -16,25 +16,25 @@ * } */ class Solution { - public boolean isSameTree(TreeNode p, TreeNode q) { - return dfs(p, q); + + public boolean isSameTree(TreeNode p, TreeNode q) { + return dfs(p, q); + } + + private boolean dfs(TreeNode p, TreeNode q) { + if (p == null && q == null) { + return true; } - - private boolean dfs(TreeNode p, TreeNode q) { - if (p == null && q == null) { - return true; - } - - if (p == null || q == null) { - return false; - } - - if (p.val != q.val) return false; - - boolean left = dfs(p.left, q.left); - boolean right = dfs(p.right, q.right); - - return left && right; + + if (p == null || q == null) { + return false; } -} + if (p.val != q.val) return false; + + boolean left = dfs(p.left, q.left); + boolean right = dfs(p.right, q.right); + + return left && right; + } +} diff --git a/java/102-Binary-Tree-Level-Order-Traversal.java b/java/102-Binary-Tree-Level-Order-Traversal.java index a220f33bb..0635d3a45 100644 --- a/java/102-Binary-Tree-Level-Order-Traversal.java +++ b/java/102-Binary-Tree-Level-Order-Traversal.java @@ -14,28 +14,29 @@ * } */ class Solution { - public List> levelOrder(TreeNode root) { - List> res = new ArrayList<>(); - Queue queue = new LinkedList<>(); - - if (root == null) return res; - - queue.add(root); - while(!queue.isEmpty()) { - int len = queue.size(); - List level = new ArrayList<>(); - for (int i = 0; i < len; i++) { - TreeNode curr = queue.poll(); - level.add(curr.val); - if (curr.left != null) { - queue.add(curr.left); - } - if (curr.right != null) { - queue.add(curr.right); - } - } - res.add(level); + + public List> levelOrder(TreeNode root) { + List> res = new ArrayList<>(); + Queue queue = new LinkedList<>(); + + if (root == null) return res; + + queue.add(root); + while (!queue.isEmpty()) { + int len = queue.size(); + List level = new ArrayList<>(); + for (int i = 0; i < len; i++) { + TreeNode curr = queue.poll(); + level.add(curr.val); + if (curr.left != null) { + queue.add(curr.left); } - return res; + if (curr.right != null) { + queue.add(curr.right); + } + } + res.add(level); } + return res; + } } diff --git a/java/104-Maximum-Depth-of-Binary-Tree.java b/java/104-Maximum-Depth-of-Binary-Tree.java index 8b2894467..18fbae70f 100644 --- a/java/104-Maximum-Depth-of-Binary-Tree.java +++ b/java/104-Maximum-Depth-of-Binary-Tree.java @@ -1,6 +1,7 @@ class Solution { - public int maxDepth(TreeNode root) { - if (root == null) return 0; - return 1+Math.max(maxDepth(root.left), maxDepth(root.right)); - } + + public int maxDepth(TreeNode root) { + if (root == null) return 0; + return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); + } } diff --git a/java/1046-Last-Stone-Weight.java b/java/1046-Last-Stone-Weight.java index 754298db7..101b0ec78 100644 --- a/java/1046-Last-Stone-Weight.java +++ b/java/1046-Last-Stone-Weight.java @@ -1,14 +1,13 @@ class Solution { - public int lastStoneWeight(int[] stones) { - PriorityQueue maxHeap = new PriorityQueue(); - for (int stone: stones) - maxHeap.add(-stone); - while (maxHeap.size()>1) { - int stone1 = maxHeap.remove(); - int stone2 = maxHeap.remove(); - if (stone1!=stone2) - maxHeap.add(stone1-stone2); - } - return maxHeap.size()!=0?(-maxHeap.remove()):0; + + public int lastStoneWeight(int[] stones) { + PriorityQueue maxHeap = new PriorityQueue(); + for (int stone : stones) maxHeap.add(-stone); + while (maxHeap.size() > 1) { + int stone1 = maxHeap.remove(); + int stone2 = maxHeap.remove(); + if (stone1 != stone2) maxHeap.add(stone1 - stone2); } + return maxHeap.size() != 0 ? (-maxHeap.remove()) : 0; + } } diff --git a/java/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.java b/java/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.java index eda2bfc2f..de532f9a8 100644 --- a/java/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.java +++ b/java/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.java @@ -14,48 +14,69 @@ * } */ class Solution { - public TreeNode buildTree(int[] preorder, int[] inorder) { - if (preorder.length == 0 || inorder.length == 0) return null; - - TreeNode root = new TreeNode(preorder[0]); - int mid = 0; - for (int i = 0; i < inorder.length; i++) { - if (preorder[0] == inorder[i]) mid = i; - } - - root.left = buildTree(Arrays.copyOfRange(preorder, 1, mid + 1), Arrays.copyOfRange(inorder, 0, mid)); - root.right = buildTree(Arrays.copyOfRange(preorder, mid + 1, preorder.length), Arrays.copyOfRange(inorder, mid + 1, inorder.length)); - - return root; + + public TreeNode buildTree(int[] preorder, int[] inorder) { + if (preorder.length == 0 || inorder.length == 0) return null; + + TreeNode root = new TreeNode(preorder[0]); + int mid = 0; + for (int i = 0; i < inorder.length; i++) { + if (preorder[0] == inorder[i]) mid = i; } + + root.left = + buildTree( + Arrays.copyOfRange(preorder, 1, mid + 1), + Arrays.copyOfRange(inorder, 0, mid) + ); + root.right = + buildTree( + Arrays.copyOfRange(preorder, mid + 1, preorder.length), + Arrays.copyOfRange(inorder, mid + 1, inorder.length) + ); + + return root; + } } // Solution without using Array copies class Solution { - Map inorderPositions = new HashMap<>(); + Map inorderPositions = new HashMap<>(); - public TreeNode buildTree(int[] preorder, int[] inorder) { - if(preorder.length < 1 || inorder.length < 1) return null; + public TreeNode buildTree(int[] preorder, int[] inorder) { + if (preorder.length < 1 || inorder.length < 1) return null; - for(int i = 0; i < inorder.length; i ++) { - inorderPositions.put(inorder[i], i); - } - - return builder(preorder, 0, 0, inorder.length-1); + for (int i = 0; i < inorder.length; i++) { + inorderPositions.put(inorder[i], i); } - public TreeNode builder(int[] preorder, int preorderIndex, int inorderLow, int inorderHigh) { - if (preorderIndex > preorder.length-1 || inorderLow > inorderHigh) return null; + return builder(preorder, 0, 0, inorder.length - 1); + } - int currentVal = preorder[preorderIndex]; - TreeNode n = new TreeNode(currentVal); - int mid = inorderPositions.get(currentVal); + public TreeNode builder( + int[] preorder, + int preorderIndex, + int inorderLow, + int inorderHigh + ) { + if ( + preorderIndex > preorder.length - 1 || inorderLow > inorderHigh + ) return null; - n.left = builder(preorder, preorderIndex+1, inorderLow, mid-1); - n.right = builder(preorder, preorderIndex + (mid - inorderLow) + 1, mid+1, inorderHigh); + int currentVal = preorder[preorderIndex]; + TreeNode n = new TreeNode(currentVal); + int mid = inorderPositions.get(currentVal); - return n; - } + n.left = builder(preorder, preorderIndex + 1, inorderLow, mid - 1); + n.right = + builder( + preorder, + preorderIndex + (mid - inorderLow) + 1, + mid + 1, + inorderHigh + ); -} \ No newline at end of file + return n; + } +} diff --git a/java/106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.java b/java/106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.java index 75091cb49..c4f035bbc 100644 --- a/java/106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.java +++ b/java/106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.java @@ -1,24 +1,58 @@ //This video helped https://www.youtube.com/watch?v=LgLRTaEMRVc&ab_channel=takeUforward class Solution { - public TreeNode buildTree(int[] inorder, int[] postorder) { - HashMap inMap = new HashMap<>(); - for (int i = 0; i inMap = new HashMap<>(); + for (int i = 0; i < inorder.length; i++) { + inMap.put(inorder[i], i); } - - public TreeNode helper(int[] inorder, int iStart, int iEnd, int[] postorder, int pStart, int pEnd, HashMap inMap) { - if (pStart>pEnd || iStart>iEnd) { - return null; - } - TreeNode root = new TreeNode(postorder[pEnd]); - int index = inMap.get(postorder[pEnd]); - int numsLeft = index-iStart; - root.left = helper(inorder, iStart, index-1, postorder, pStart, pStart+numsLeft-1, inMap); - root.right = helper(inorder, index+1, iEnd, postorder, pStart+numsLeft, pEnd-1, inMap); - return root; + return helper( + inorder, + 0, + inorder.length - 1, + postorder, + 0, + postorder.length - 1, + inMap + ); + } + + public TreeNode helper( + int[] inorder, + int iStart, + int iEnd, + int[] postorder, + int pStart, + int pEnd, + HashMap inMap + ) { + if (pStart > pEnd || iStart > iEnd) { + return null; } - + TreeNode root = new TreeNode(postorder[pEnd]); + int index = inMap.get(postorder[pEnd]); + int numsLeft = index - iStart; + root.left = + helper( + inorder, + iStart, + index - 1, + postorder, + pStart, + pStart + numsLeft - 1, + inMap + ); + root.right = + helper( + inorder, + index + 1, + iEnd, + postorder, + pStart + numsLeft, + pEnd - 1, + inMap + ); + return root; + } } diff --git a/java/107-Binary-Tree-Level-Order-Traversal-II.java b/java/107-Binary-Tree-Level-Order-Traversal-II.java index f13448893..42d01dd40 100644 --- a/java/107-Binary-Tree-Level-Order-Traversal-II.java +++ b/java/107-Binary-Tree-Level-Order-Traversal-II.java @@ -1,26 +1,27 @@ -//Same just reverse in the end. +//Same just reverse in the end. //Reversing in the end is better than using add(0, E) in case of arraylist as it's an O(1) operation. class Solution { - public List> levelOrderBottom(TreeNode root) { - List> ans = new ArrayList<>(); - if (root == null) return ans; - Queue q = new LinkedList<>(); - q.offer(root); - while (!q.isEmpty()) { - List level = new ArrayList<>(); - int size = q.size(); - for (int i = 0; i> levelOrderBottom(TreeNode root) { + List> ans = new ArrayList<>(); + if (root == null) return ans; + Queue q = new LinkedList<>(); + q.offer(root); + while (!q.isEmpty()) { + List level = new ArrayList<>(); + int size = q.size(); + for (int i = 0; i < size; i++) { + TreeNode cur = q.poll(); + level.add(cur.val); + if (cur.left != null) q.offer(cur.left); + if (cur.right != null) q.offer(cur.right); + } + ans.add(level); } + int i = 0, j = ans.size() - 1; + //reverse the list + Collections.reverse(ans); + return ans; + } } diff --git a/java/11-Container-With-Most-Water.java b/java/11-Container-With-Most-Water.java index 1742d11c2..53788fdb6 100644 --- a/java/11-Container-With-Most-Water.java +++ b/java/11-Container-With-Most-Water.java @@ -1,18 +1,19 @@ class Solution { - public int maxArea(int[] height) { - int left = 0; - int right = height.length - 1; - int res = 0; - while (left < right) { - int containerLength = right - left; - int area = containerLength * Math.min(height[left], height[right]); - res = Math.max(res, area); - if (height[left] < height[right]) { - left++; - } else { - right--; - } - } - return res; + + public int maxArea(int[] height) { + int left = 0; + int right = height.length - 1; + int res = 0; + while (left < right) { + int containerLength = right - left; + int area = containerLength * Math.min(height[left], height[right]); + res = Math.max(res, area); + if (height[left] < height[right]) { + left++; + } else { + right--; + } } -} \ No newline at end of file + return res; + } +} diff --git a/java/110-Balanced-Binary-Tree.java b/java/110-Balanced-Binary-Tree.java index bd0184e5e..14d762990 100644 --- a/java/110-Balanced-Binary-Tree.java +++ b/java/110-Balanced-Binary-Tree.java @@ -1,19 +1,27 @@ package com.coding.patterns.tree; class BalancedBinaryTree { - private static Pair dfs(TreeNode root) { - if (root == null) { - return new Pair(true, 0); - } - - var left = dfs(root.left); - var right = dfs(root.right); - - var balanced = left.getKey() && right.getKey() && (Math.abs(left.getValue() - right.getValue()) <= 1); - - return new Pair(balanced, 1 + Math.max(left.getValue(), right.getValue())); - } - public static boolean isBalanced(TreeNode root) { - return dfs(root).getKey(); + + private static Pair dfs(TreeNode root) { + if (root == null) { + return new Pair(true, 0); } + + var left = dfs(root.left); + var right = dfs(root.right); + + var balanced = + left.getKey() && + right.getKey() && + (Math.abs(left.getValue() - right.getValue()) <= 1); + + return new Pair( + balanced, + 1 + Math.max(left.getValue(), right.getValue()) + ); + } + + public static boolean isBalanced(TreeNode root) { + return dfs(root).getKey(); + } } diff --git a/java/1143-Longest-Common-Subsequence.java b/java/1143-Longest-Common-Subsequence.java index 1d1ad663f..da7c73722 100644 --- a/java/1143-Longest-Common-Subsequence.java +++ b/java/1143-Longest-Common-Subsequence.java @@ -1,19 +1,20 @@ //memoized version class Solution { - public int longestCommonSubsequence(String text1, String text2) { - int[][] dp = new int[text1.length()][text2.length()]; - return LCS(text1, text2, 0, 0, dp); - } - - public int LCS(String s1, String s2, int i, int j, int[][] dp) { - if (i>=s1.length() || j>=s2.length()) return 0; - else if (dp[i][j]!=0) return dp[i][j]; - else if (s1.charAt(i) == s2.charAt(j)) return 1+LCS(s1, s2, i+1, j+1, dp); - else{ - dp[i][j] = Math.max(LCS(s1, s2, i+1, j, dp), LCS(s1, s2, i, j+1, dp)); - return dp[i][j]; - } + + public int longestCommonSubsequence(String text1, String text2) { + int[][] dp = new int[text1.length()][text2.length()]; + return LCS(text1, text2, 0, 0, dp); + } + + public int LCS(String s1, String s2, int i, int j, int[][] dp) { + if (i >= s1.length() || j >= s2.length()) return 0; else if ( + dp[i][j] != 0 + ) return dp[i][j]; else if (s1.charAt(i) == s2.charAt(j)) return ( + 1 + LCS(s1, s2, i + 1, j + 1, dp) + ); else { + dp[i][j] = Math.max(LCS(s1, s2, i + 1, j, dp), LCS(s1, s2, i, j + 1, dp)); + return dp[i][j]; } - + } } diff --git a/java/1155-Number-of-Dice-Rolls-With-Target-Sum.java b/java/1155-Number-of-Dice-Rolls-With-Target-Sum.java index 94515c827..42a5be832 100644 --- a/java/1155-Number-of-Dice-Rolls-With-Target-Sum.java +++ b/java/1155-Number-of-Dice-Rolls-With-Target-Sum.java @@ -1,26 +1,22 @@ class Solution { - int mod = 1000000007; - public int numRollsToTarget(int n, int k, int target) { - if (target>n*k || target n * k || target < n) return 0; + if (n == 1) return target < n ? 0 : 1; + int[][] dp = new int[n + 1][target + 1]; + return helper(n, k, target, dp); + } + + public int helper(int n, int k, int target, int[][] dp) { + if (target > n * k || target < n) return 0; + if (target == 0 && n == 0) return 1; + if (dp[n][target] != 0) return dp[n][target]; + int sum = 0; + for (int i = 1; i <= k; i++) { + sum = (sum + helper(n - 1, k, target - i, dp)) % mod; } - - public int helper(int n, int k , int target, int[][] dp) { - if (target>n*k || targetarrChars[i]) - flag = false; - } - if (flag) ans += s.length(); - } - return ans; + + public int countCharacters(String[] words, String chars) { + int[] arrChars = new int[26]; + for (int i = 0; i < chars.length(); i++) { + arrChars[chars.charAt(i) - 'a']++; + } + int ans = 0; + for (String s : words) { + boolean flag = true; + int[] arrS = new int[26]; + for (int i = 0; i < s.length(); i++) { + arrS[s.charAt(i) - 'a']++; + } + for (int i = 0; i < 26; i++) { + if (arrS[i] > arrChars[i]) flag = false; + } + if (flag) ans += s.length(); } + return ans; + } } diff --git a/java/119-Pascal's-Triangle-II.java b/java/119-Pascal's-Triangle-II.java index cf42870d3..1a1ac2767 100644 --- a/java/119-Pascal's-Triangle-II.java +++ b/java/119-Pascal's-Triangle-II.java @@ -1,24 +1,21 @@ -//Approach 1 using recursion +//Approach 1 using recursion class Solution { - public List getRow(int rowIndex) { - List ans = new ArrayList<>(); - int[][] dp = new int[rowIndex+1][rowIndex+1]; - for (int i = 0; i<=rowIndex; i++) { - ans.add(value(rowIndex, i, dp)); - } - return ans; - } - - - public int value(int row, int col, int[][] dp) { - if (row == 0 || col == 0 || col == row) - return 1; - if (dp[row][col]!=0) return dp[row][col]; - dp[row][col] = value(row-1, col-1, dp)+value(row-1, col, dp); - return dp[row][col]; + + public List getRow(int rowIndex) { + List ans = new ArrayList<>(); + int[][] dp = new int[rowIndex + 1][rowIndex + 1]; + for (int i = 0; i <= rowIndex; i++) { + ans.add(value(rowIndex, i, dp)); } - -} + return ans; + } + public int value(int row, int col, int[][] dp) { + if (row == 0 || col == 0 || col == row) return 1; + if (dp[row][col] != 0) return dp[row][col]; + dp[row][col] = value(row - 1, col - 1, dp) + value(row - 1, col, dp); + return dp[row][col]; + } +} //todo: add bottom up approach diff --git a/java/121-Best-Time-to-Buy-and-Sell-Stock.java b/java/121-Best-Time-to-Buy-and-Sell-Stock.java index 082ca5f4f..d367f3d4f 100644 --- a/java/121-Best-Time-to-Buy-and-Sell-Stock.java +++ b/java/121-Best-Time-to-Buy-and-Sell-Stock.java @@ -1,11 +1,12 @@ class Solution { - public int maxProfit(int[] prices) { - int min = Integer.MAX_VALUE; - int ans = Integer.MIN_VALUE; - for (int val: prices) { - min = Math.min(min, val); - ans = Math.max(ans, val - min); - } - return ans; + + public int maxProfit(int[] prices) { + int min = Integer.MAX_VALUE; + int ans = Integer.MIN_VALUE; + for (int val : prices) { + min = Math.min(min, val); + ans = Math.max(ans, val - min); } + return ans; + } } diff --git a/java/124-Binary-Tree-Maximum-Path-Sum.java b/java/124-Binary-Tree-Maximum-Path-Sum.java index 22d94a98f..2b0a68bac 100644 --- a/java/124-Binary-Tree-Maximum-Path-Sum.java +++ b/java/124-Binary-Tree-Maximum-Path-Sum.java @@ -16,28 +16,27 @@ * } */ class Solution { - - int[] res = new int[1]; - - public int maxPathSum(TreeNode root) { - res[0] = root.val; - dfs(root); - return res[0]; - } - - private int dfs(TreeNode node) { - if (node == null) return 0; - - int leftMax = dfs(node.left); - int rightMax = dfs(node.right); - - leftMax = Math.max(leftMax, 0); - rightMax = Math.max(rightMax, 0); - - int allMax = leftMax + rightMax + node.val; - res[0] = Math.max(res[0], allMax); - - - return node.val + Math.max(leftMax, rightMax); - } -} \ No newline at end of file + + int[] res = new int[1]; + + public int maxPathSum(TreeNode root) { + res[0] = root.val; + dfs(root); + return res[0]; + } + + private int dfs(TreeNode node) { + if (node == null) return 0; + + int leftMax = dfs(node.left); + int rightMax = dfs(node.right); + + leftMax = Math.max(leftMax, 0); + rightMax = Math.max(rightMax, 0); + + int allMax = leftMax + rightMax + node.val; + res[0] = Math.max(res[0], allMax); + + return node.val + Math.max(leftMax, rightMax); + } +} diff --git a/java/1275-Find-Winner-on-a-Tic-Tac-Toe-Game.java b/java/1275-Find-Winner-on-a-Tic-Tac-Toe-Game.java index 41fa26079..17c93eb62 100644 --- a/java/1275-Find-Winner-on-a-Tic-Tac-Toe-Game.java +++ b/java/1275-Find-Winner-on-a-Tic-Tac-Toe-Game.java @@ -1,33 +1,31 @@ class Solution { - public String tictactoe(int[][] moves) { - int[][][] result = new int[2][2][3]; - int[][] diag1 = new int[2][1]; - int[][] diag2 = new int[2][1]; - - int p = 0; - for (int i = 0; i < moves.length; i++) { - int r = moves[i][0]; - int c = moves[i][1]; - - if (++result[p][0][r] == 3) return getWinner(p); - if (++result[p][1][c] == 3) return getWinner(p); - - if (r == c) - if (++diag1[p][0] == 3) - return getWinner(p); - - if ((r == 1 && c == 1) || (r == 0 && c == 2) || (r == 2 && c == 0)) - if (++diag2[p][0] == 3) - return getWinner(p); - - if (p == 0) p = 1; - else p = 0; - } - - return moves.length == 9 ? "Draw" : "Pending"; - } - - private String getWinner(int p) { - return p == 0 ? "A" : "B"; + + public String tictactoe(int[][] moves) { + int[][][] result = new int[2][2][3]; + int[][] diag1 = new int[2][1]; + int[][] diag2 = new int[2][1]; + + int p = 0; + for (int i = 0; i < moves.length; i++) { + int r = moves[i][0]; + int c = moves[i][1]; + + if (++result[p][0][r] == 3) return getWinner(p); + if (++result[p][1][c] == 3) return getWinner(p); + + if (r == c) if (++diag1[p][0] == 3) return getWinner(p); + + if ((r == 1 && c == 1) || (r == 0 && c == 2) || (r == 2 && c == 0)) if ( + ++diag2[p][0] == 3 + ) return getWinner(p); + + if (p == 0) p = 1; else p = 0; } + + return moves.length == 9 ? "Draw" : "Pending"; + } + + private String getWinner(int p) { + return p == 0 ? "A" : "B"; + } } diff --git a/java/128-Longest-Consecutive-Sequence.java b/java/128-Longest-Consecutive-Sequence.java index 64dd5176a..3b0b6879d 100644 --- a/java/128-Longest-Consecutive-Sequence.java +++ b/java/128-Longest-Consecutive-Sequence.java @@ -1,19 +1,20 @@ class Solution { - public int longestConsecutive(int[] nums) { - if (nums.length == 0) return 0; - HashSet set = new HashSet<>(); - int ans = 1; - for (int num: nums) set.add(num); - for (int num: nums) { - if (!set.contains(num-1)) { - int count = 1; - while (set.contains(num+1)) { - num++; - count++; - } - ans = Math.max(count, ans); - } + + public int longestConsecutive(int[] nums) { + if (nums.length == 0) return 0; + HashSet set = new HashSet<>(); + int ans = 1; + for (int num : nums) set.add(num); + for (int num : nums) { + if (!set.contains(num - 1)) { + int count = 1; + while (set.contains(num + 1)) { + num++; + count++; } - return ans; + ans = Math.max(count, ans); + } } + return ans; + } } diff --git a/java/128. Longest Consecutive Sequence.java b/java/128. Longest Consecutive Sequence.java index 5179a5fda..ea10e6155 100644 --- a/java/128. Longest Consecutive Sequence.java +++ b/java/128. Longest Consecutive Sequence.java @@ -1,34 +1,34 @@ class Solution { - public int longestConsecutive(int[] nums) { - Set set = new HashSet<>(); - int max = -1; - int min = 1000000000; - - // Find min and max from array & add each to set - for (int i : nums) { - set.add(i); - max = Math.max(max, i); - min = Math.min(min, i); - } - - int c = 0; // count streak - int res = 0; // longest streak - for (int i = min; i <= max; ++i) { - // Check if set contains ith value; increment count & remove from set - if (set.contains(i)) { - c++; - set.remove(i); - } - else { - // If not found set count to 0 - c = 0; - } - // Find longest streak at every step in case we break out from loop - res = Math.max(res, c); - - // If set size is less than current longest streak break as we wont get any longer streak - if (set.size() <= res && c == 0) break; - } - return res; + + public int longestConsecutive(int[] nums) { + Set set = new HashSet<>(); + int max = -1; + int min = 1000000000; + + // Find min and max from array & add each to set + for (int i : nums) { + set.add(i); + max = Math.max(max, i); + min = Math.min(min, i); } + + int c = 0; // count streak + int res = 0; // longest streak + for (int i = min; i <= max; ++i) { + // Check if set contains ith value; increment count & remove from set + if (set.contains(i)) { + c++; + set.remove(i); + } else { + // If not found set count to 0 + c = 0; + } + // Find longest streak at every step in case we break out from loop + res = Math.max(res, c); + + // If set size is less than current longest streak break as we wont get any longer streak + if (set.size() <= res && c == 0) break; + } + return res; + } } diff --git a/java/130-Surrounded-Regions.java b/java/130-Surrounded-Regions.java index 33722147a..cd5626aea 100644 --- a/java/130-Surrounded-Regions.java +++ b/java/130-Surrounded-Regions.java @@ -1,37 +1,40 @@ class Solution { - public void solve(char[][] board) { - int nRows = board.length; - int nCols = board[0].length; - - // 1a) Capture unsurrounded regions - top and bottom row (O -> T) - for (int i = 0; i < nCols; i++) { - if (board[0][i] == 'O') dfs(board, 0, i); - if (board[nRows-1][i] == 'O') dfs(board, nRows-1, i); - } - - // 1b) Capture unsurrounded regions - Left and right columns (O -> T) - for (int i = 0; i < nRows; i++) { - if (board[i][0] == 'O') dfs(board, i, 0); - if (board[i][nCols-1] == 'O') dfs(board, i, nCols-1); - } - - for (int r = 0; r < nRows; r++) { - for (int c = 0; c < nCols; c++) { - if (board[r][c] == 'O') board[r][c] = 'X'; // 2) Capture surrounded regions (O -> X) - if (board[r][c] == 'T') board[r][c] = 'O'; // 3) Uncapture unsurrounded regions (T- O) - } - } + + public void solve(char[][] board) { + int nRows = board.length; + int nCols = board[0].length; + + // 1a) Capture unsurrounded regions - top and bottom row (O -> T) + for (int i = 0; i < nCols; i++) { + if (board[0][i] == 'O') dfs(board, 0, i); + if (board[nRows - 1][i] == 'O') dfs(board, nRows - 1, i); } - - private void dfs(char[][] board, int r, int c) { - int nRows = board.length; - int nCols = board[0].length; - if (r < 0 || c < 0 || r >= nRows || c >= nCols || board[r][c] != 'O') return; - - board[r][c] = 'T'; - dfs(board, r+1, c); - dfs(board, r-1, c); - dfs(board, r, c+1); - dfs(board, r, c-1); - } + + // 1b) Capture unsurrounded regions - Left and right columns (O -> T) + for (int i = 0; i < nRows; i++) { + if (board[i][0] == 'O') dfs(board, i, 0); + if (board[i][nCols - 1] == 'O') dfs(board, i, nCols - 1); + } + + for (int r = 0; r < nRows; r++) { + for (int c = 0; c < nCols; c++) { + if (board[r][c] == 'O') board[r][c] = 'X'; // 2) Capture surrounded regions (O -> X) + if (board[r][c] == 'T') board[r][c] = 'O'; // 3) Uncapture unsurrounded regions (T- O) + } + } + } + + private void dfs(char[][] board, int r, int c) { + int nRows = board.length; + int nCols = board[0].length; + if ( + r < 0 || c < 0 || r >= nRows || c >= nCols || board[r][c] != 'O' + ) return; + + board[r][c] = 'T'; + dfs(board, r + 1, c); + dfs(board, r - 1, c); + dfs(board, r, c + 1); + dfs(board, r, c - 1); + } } diff --git a/java/131-Palindrome-Partitioning.java b/java/131-Palindrome-Partitioning.java index d4c13c802..eb108f9cb 100644 --- a/java/131-Palindrome-Partitioning.java +++ b/java/131-Palindrome-Partitioning.java @@ -1,26 +1,26 @@ public class Solution { - public List> partition(String s) { - List> res = new ArrayList>(); - if (s.equals("")) { - res.add(new ArrayList()); - return res; - } - for (int i = 0; i < s.length(); i++) { - if (isPalindrome(s, i + 1)) { - for (List list : partition(s.substring(i+1))) { - list.add(0, s.substring(0, i + 1)); - res.add(list); - } - } - } - return res; + + public List> partition(String s) { + List> res = new ArrayList>(); + if (s.equals("")) { + res.add(new ArrayList()); + return res; } - - public boolean isPalindrome(String s, int n) { - for (int i = 0; i < n / 2; i++) { - if (s.charAt(i) != s.charAt(n - i - 1)) - return false; + for (int i = 0; i < s.length(); i++) { + if (isPalindrome(s, i + 1)) { + for (List list : partition(s.substring(i + 1))) { + list.add(0, s.substring(0, i + 1)); + res.add(list); } - return true; + } + } + return res; + } + + public boolean isPalindrome(String s, int n) { + for (int i = 0; i < n / 2; i++) { + if (s.charAt(i) != s.charAt(n - i - 1)) return false; } -} \ No newline at end of file + return true; + } +} diff --git a/java/133-Clone-Graph.java b/java/133-Clone-Graph.java index 9e152df76..721f4c483 100644 --- a/java/133-Clone-Graph.java +++ b/java/133-Clone-Graph.java @@ -1,17 +1,15 @@ class Solution { - - public HashMap map = new HashMap<>(); - - public Node cloneGraph(Node node) { - if (node == null) - return null; - if (map.containsKey(node.val)) - return map.get(node.val); - Node newNode = new Node(node.val, new ArrayList()); - map.put(node.val, newNode); - for (Node neighbor: node.neighbors) { - newNode.neighbors.add(cloneGraph(neighbor)); - } - return newNode; + + public HashMap map = new HashMap<>(); + + public Node cloneGraph(Node node) { + if (node == null) return null; + if (map.containsKey(node.val)) return map.get(node.val); + Node newNode = new Node(node.val, new ArrayList()); + map.put(node.val, newNode); + for (Node neighbor : node.neighbors) { + newNode.neighbors.add(cloneGraph(neighbor)); } + return newNode; + } } diff --git a/java/134-Gas-Station.java b/java/134-Gas-Station.java index 754dc0cca..77dfd8bf2 100644 --- a/java/134-Gas-Station.java +++ b/java/134-Gas-Station.java @@ -1,18 +1,19 @@ class Solution { - public int canCompleteCircuit(int[] gas, int[] cost) { - int sGas=0,sCost=0,res=0,total=0; - for(int i=0;i map = new HashMap<>(); - while (cur!=null) { - map.put(cur, new Node(cur.val)); - cur = cur.next; - } - cur = head; - while (cur!=null) { - map.get(cur).next = map.get(cur.next); - map.get(cur).random = map.get(cur.random); - cur = cur.next; - } - return map.get(head); + + public Node copyRandomList(Node head) { + Node cur = head; + HashMap map = new HashMap<>(); + while (cur != null) { + map.put(cur, new Node(cur.val)); + cur = cur.next; } + cur = head; + while (cur != null) { + map.get(cur).next = map.get(cur.next); + map.get(cur).random = map.get(cur.random); + cur = cur.next; + } + return map.get(head); + } } diff --git a/java/139-Word- Break.java b/java/139-Word- Break.java index 4070f136a..620b30680 100644 --- a/java/139-Word- Break.java +++ b/java/139-Word- Break.java @@ -1,25 +1,28 @@ class Solution { - public boolean wordBreak(String s, List wordDict) { - boolean[] dp = new boolean[s.length() + 1]; - Set workDictSet = new HashSet<>(wordDict); - - for(int i=0; i wordDict) { + boolean[] dp = new boolean[s.length() + 1]; + Set workDictSet = new HashSet<>(wordDict); + + for (int i = 0; i < dp.length; i++) { + dp[i] = false; + } + + dp[s.length()] = true; + + for (int i = s.length() - 1; i >= 0; i--) { + for (String word : wordDict) { + if ( + ((i + word.length()) <= s.length()) && + (s.substring(i, i + word.length()).startsWith(word)) + ) { + dp[i] = dp[i + word.length()]; } - - dp[s.length()] = true; - - for(int i= s.length() -1 ; i>=0; i--){ - for(String word : wordDict){ - if( ((i + word.length()) <= s.length()) - && (s.substring(i , i + word.length()).startsWith(word))){ - dp[i] = dp[i + word.length()]; - } - if(dp[i]){ - break; - } - } + if (dp[i]) { + break; } - return dp[0]; + } } + return dp[0]; + } } diff --git a/java/141. Linked List Cycle.java b/java/141. Linked List Cycle.java index 0e608055c..01bcdd925 100644 --- a/java/141. Linked List Cycle.java +++ b/java/141. Linked List Cycle.java @@ -1,14 +1,15 @@ //Fast and slow pointer public class Solution { - public boolean hasCycle(ListNode head) { - ListNode fast = head; - ListNode slow = head; - while (fast!=null && fast.next!=null) { - fast = fast.next.next; - slow = slow.next; - if (fast == slow) return true; - } - return false; + + public boolean hasCycle(ListNode head) { + ListNode fast = head; + ListNode slow = head; + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + if (fast == slow) return true; } + return false; + } } diff --git a/java/143-Reorder-List.java b/java/143-Reorder-List.java index da9b68127..26ac6334a 100644 --- a/java/143-Reorder-List.java +++ b/java/143-Reorder-List.java @@ -9,32 +9,33 @@ * } */ class Solution { - public void reorderList(ListNode head) { - ListNode slow = head; - ListNode fast = head.next; - while(fast != null && fast.next != null) { - slow = slow.next; - fast = fast.next.next; - } - - ListNode second = slow.next; - ListNode prev = slow.next = null; - while (second != null) { - ListNode tmp = second.next; - second.next = prev; - prev = second; - second = tmp; - } - - ListNode first = head; - second = prev; - while (second != null) { - ListNode tmp1 = first.next; - ListNode tmp2 = second.next; - first.next = second; - second.next = tmp1; - first = tmp1; - second = tmp2; - } + + public void reorderList(ListNode head) { + ListNode slow = head; + ListNode fast = head.next; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; } + + ListNode second = slow.next; + ListNode prev = slow.next = null; + while (second != null) { + ListNode tmp = second.next; + second.next = prev; + prev = second; + second = tmp; + } + + ListNode first = head; + second = prev; + while (second != null) { + ListNode tmp1 = first.next; + ListNode tmp2 = second.next; + first.next = second; + second.next = tmp1; + first = tmp1; + second = tmp2; + } + } } diff --git a/java/1448-Count-Good-Nodes-in-Binary-Tree.java b/java/1448-Count-Good-Nodes-in-Binary-Tree.java index 096ab6b6e..b091d88a0 100644 --- a/java/1448-Count-Good-Nodes-in-Binary-Tree.java +++ b/java/1448-Count-Good-Nodes-in-Binary-Tree.java @@ -1,20 +1,17 @@ class Solution { - public int goodNodes(TreeNode root) { - return helper(root, -99999); - - } - - public int helper(TreeNode root, int max) { - - if (root == null) return 0; - - int res = root.val>=max?1:0; - - res += helper(root.left, Math.max(root.val, max)); - res += helper(root.right, Math.max(root.val, max)); - - return res; - - } - + + public int goodNodes(TreeNode root) { + return helper(root, -99999); + } + + public int helper(TreeNode root, int max) { + if (root == null) return 0; + + int res = root.val >= max ? 1 : 0; + + res += helper(root.left, Math.max(root.val, max)); + res += helper(root.right, Math.max(root.val, max)); + + return res; + } } diff --git a/java/146-LRU-Cache.java b/java/146-LRU-Cache.java index b605094cf..21ecff040 100644 --- a/java/146-LRU-Cache.java +++ b/java/146-LRU-Cache.java @@ -1,91 +1,79 @@ class LRUCache { - private Map cache; - private int capacity; - - private Node left; - private Node right; - - public LRUCache(int capacity) { - this.capacity = capacity; - cache = new HashMap<>(); - - //left = LRU , right = most recent - this.left = new Node(0,0); - this.right = new Node(0,0); - this.left.next = this.right; - this.right.prev = this.left; - - } - - public int get(int key) { - - if(cache.containsKey(key)){ - remove(cache.get(key)); - insert(cache.get(key)); - return cache.get(key).val; - - } else{ - return -1; - } - + private Map cache; + private int capacity; + + private Node left; + private Node right; + + public LRUCache(int capacity) { + this.capacity = capacity; + cache = new HashMap<>(); + + //left = LRU , right = most recent + this.left = new Node(0, 0); + this.right = new Node(0, 0); + this.left.next = this.right; + this.right.prev = this.left; + } + + public int get(int key) { + if (cache.containsKey(key)) { + remove(cache.get(key)); + insert(cache.get(key)); + return cache.get(key).val; + } else { + return -1; } - - public void put(int key, int value) { - - if(cache.containsKey(key)){ - remove(cache.get(key)); - } - cache.put(key , new Node(key , value)); - insert(cache.get(key)); - - if(cache.size() > capacity){ - // remove from the list and delte the LRU from the hashmap - Node lru = this.left.next; - remove(lru); - cache.remove(lru.key); - - } - - + } + + public void put(int key, int value) { + if (cache.containsKey(key)) { + remove(cache.get(key)); } - - // remove node from list - public void remove(Node node) { - - Node prev = node.prev; - Node next = node.next; - - prev.next = next; - next.prev = prev; + cache.put(key, new Node(key, value)); + insert(cache.get(key)); + + if (cache.size() > capacity) { + // remove from the list and delte the LRU from the hashmap + Node lru = this.left.next; + remove(lru); + cache.remove(lru.key); } - - // insert node at right - public void insert(Node node) { - - Node prev = this.right.prev; - Node next = this.right; - - - prev.next = node; - next.prev = node; - - node.next =next; - node.prev =prev; - - - + } + + // remove node from list + public void remove(Node node) { + Node prev = node.prev; + Node next = node.next; + + prev.next = next; + next.prev = prev; + } + + // insert node at right + public void insert(Node node) { + Node prev = this.right.prev; + Node next = this.right; + + prev.next = node; + next.prev = node; + + node.next = next; + node.prev = prev; + } + + private class Node { + + private int key; + private int val; + + Node next; + Node prev; + + public Node(int key, int val) { + this.key = key; + this.val = val; } - private class Node{ - private int key; - private int val; - - Node next; - Node prev; - - public Node(int key , int val){ - this.key = key; - this.val = val; - } } -} \ No newline at end of file +} diff --git a/java/15-3Sum.java b/java/15-3Sum.java index e0329ec78..db815c555 100644 --- a/java/15-3Sum.java +++ b/java/15-3Sum.java @@ -1,39 +1,40 @@ class Solution { -//2 pointers - public List> threeSum(int[] nums) { - Arrays.sort(nums); - LinkedList> sol = new LinkedList>(); - for (int i = 0; i < nums.length - 2; i++) { - if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) { - int target = 0 - nums[i]; - int left = i + 1; - int right = nums.length - 1; + //2 pointers + public List> threeSum(int[] nums) { + Arrays.sort(nums); + LinkedList> sol = new LinkedList>(); - while (left < right) { - if (nums[left] + nums[right] == target) { - ArrayList miniSol = new ArrayList<>(); - miniSol.add(nums[i]); - miniSol.add(nums[left]); - miniSol.add(nums[right]); - sol.add(miniSol); - while (left < right && nums[left] == nums[left + 1]) { - left++; - } - while (left < right && nums[right] == nums[right - 1]) { - right--; - } - left++; - right--; - } else if (nums[left] + nums[right] > target) { - right--; - } else { - left++; - } - } + for (int i = 0; i < nums.length - 2; i++) { + if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) { + int target = 0 - nums[i]; + int left = i + 1; + int right = nums.length - 1; + + while (left < right) { + if (nums[left] + nums[right] == target) { + ArrayList miniSol = new ArrayList<>(); + miniSol.add(nums[i]); + miniSol.add(nums[left]); + miniSol.add(nums[right]); + sol.add(miniSol); + while (left < right && nums[left] == nums[left + 1]) { + left++; + } + while (left < right && nums[right] == nums[right - 1]) { + right--; } + left++; + right--; + } else if (nums[left] + nums[right] > target) { + right--; + } else { + left++; + } } - - return sol; + } } + + return sol; + } } diff --git a/java/150-Evaluate-Reverse-Polish-Notation.java b/java/150-Evaluate-Reverse-Polish-Notation.java index 5847619a6..747a84ddb 100644 --- a/java/150-Evaluate-Reverse-Polish-Notation.java +++ b/java/150-Evaluate-Reverse-Polish-Notation.java @@ -1,23 +1,24 @@ class Solution { - public int evalRPN(String[] tokens) { - Stack stack = new Stack<>(); - for (String token: tokens) { - if (token.equals("+")) { - stack.add(stack.pop()+stack.pop()); - } else if (token.equals("-")) { - int a = stack.pop(); - int b = stack.pop(); - stack.add(b-a); - } else if (token.equals("*")) { - stack.add(stack.pop()*stack.pop()); - } else if (token.equals("/")) { - int a = stack.pop(); - int b = stack.pop(); - stack.add(b/a); - } else { - stack.add(Integer.parseInt(token)); - } - } - return stack.pop(); + + public int evalRPN(String[] tokens) { + Stack stack = new Stack<>(); + for (String token : tokens) { + if (token.equals("+")) { + stack.add(stack.pop() + stack.pop()); + } else if (token.equals("-")) { + int a = stack.pop(); + int b = stack.pop(); + stack.add(b - a); + } else if (token.equals("*")) { + stack.add(stack.pop() * stack.pop()); + } else if (token.equals("/")) { + int a = stack.pop(); + int b = stack.pop(); + stack.add(b / a); + } else { + stack.add(Integer.parseInt(token)); + } } + return stack.pop(); + } } diff --git a/java/152-Maximum-Product-Subarray.java b/java/152-Maximum-Product-Subarray.java index 7fb4d002c..ccbd0ee5b 100644 --- a/java/152-Maximum-Product-Subarray.java +++ b/java/152-Maximum-Product-Subarray.java @@ -1,17 +1,18 @@ class Solution { - public int maxProduct(int[] nums) { - if (nums.length == 1) return nums[0]; - - int res = nums[0]; - int max = 1; - int min = 1; - - for (int n: nums) { - int tmp = max * n; - max = Math.max(n, Math.max(tmp, min * n)); - min = Math.min(n, Math.min(tmp, min * n)); - res = Math.max(res, max); - } - return res; + + public int maxProduct(int[] nums) { + if (nums.length == 1) return nums[0]; + + int res = nums[0]; + int max = 1; + int min = 1; + + for (int n : nums) { + int tmp = max * n; + max = Math.max(n, Math.max(tmp, min * n)); + min = Math.min(n, Math.min(tmp, min * n)); + res = Math.max(res, max); } + return res; + } } diff --git a/java/153-Find-Minimum-in-Rotated-Sorted-Array.java b/java/153-Find-Minimum-in-Rotated-Sorted-Array.java index 5e9c56b6d..3d5f18399 100644 --- a/java/153-Find-Minimum-in-Rotated-Sorted-Array.java +++ b/java/153-Find-Minimum-in-Rotated-Sorted-Array.java @@ -1,20 +1,21 @@ class Solution { - public int findMin(int[] nums) { - int l = 0; - int r = nums.length - 1; - - while (l <= r) { - if (nums[l] <= nums[r]) { - return nums[l]; - } - - int mid = (l + r) / 2; - if (nums[mid] >= nums[l]) { - l = mid + 1; - } else { - r = mid; - } - } - return 0; + + public int findMin(int[] nums) { + int l = 0; + int r = nums.length - 1; + + while (l <= r) { + if (nums[l] <= nums[r]) { + return nums[l]; + } + + int mid = (l + r) / 2; + if (nums[mid] >= nums[l]) { + l = mid + 1; + } else { + r = mid; + } } + return 0; + } } diff --git a/java/155-Min-Stack.java b/java/155-Min-Stack.java index 563f0d9ad..817d9de7e 100644 --- a/java/155-Min-Stack.java +++ b/java/155-Min-Stack.java @@ -1,39 +1,34 @@ class MinStack { - private Stack stack; - private Stack minStack; - - public MinStack() { - stack = new Stack<>(); - minStack = new Stack<>(); - - } - - public void push(int val) { - stack.push(val); - - // The min stack may be empty, so we need to check it - val = Math.min(val, minStack.isEmpty() ? val : minStack.peek()); - minStack.push(val); - - } - - public void pop() { - stack.pop(); - minStack.pop(); - - } - - public int top() { - return stack.peek(); - } - - public int getMin() { - return minStack.peek(); - - } + private Stack stack; + private Stack minStack; + + public MinStack() { + stack = new Stack<>(); + minStack = new Stack<>(); + } + + public void push(int val) { + stack.push(val); + + // The min stack may be empty, so we need to check it + val = Math.min(val, minStack.isEmpty() ? val : minStack.peek()); + minStack.push(val); + } + + public void pop() { + stack.pop(); + minStack.pop(); + } + + public int top() { + return stack.peek(); + } + + public int getMin() { + return minStack.peek(); + } } - /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); @@ -41,4 +36,4 @@ public int getMin() { * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); - */ \ No newline at end of file + */ diff --git a/java/167-Two-Sum-II.java b/java/167-Two-Sum-II.java index 482802882..dfa76320a 100644 --- a/java/167-Two-Sum-II.java +++ b/java/167-Two-Sum-II.java @@ -1,24 +1,24 @@ class Solution { - public int[] twoSum(int[] numbers, int target) { - int a_pointer = 0; - int b_pointer = numbers.length - 1; - int num_a, num_b; - - while(a_pointer < b_pointer) { - num_a = numbers[a_pointer]; - num_b = numbers[b_pointer]; - - if(num_a + num_b == target) break; - - if(num_a + num_b < target) { - a_pointer++; - continue; - } - - b_pointer--; - - } - - return new int[]{a_pointer + 1, b_pointer + 1}; + + public int[] twoSum(int[] numbers, int target) { + int a_pointer = 0; + int b_pointer = numbers.length - 1; + int num_a, num_b; + + while (a_pointer < b_pointer) { + num_a = numbers[a_pointer]; + num_b = numbers[b_pointer]; + + if (num_a + num_b == target) break; + + if (num_a + num_b < target) { + a_pointer++; + continue; + } + + b_pointer--; } + + return new int[] { a_pointer + 1, b_pointer + 1 }; + } } diff --git a/java/17-Letter-Combinations-of-a-Phone-Number.java b/java/17-Letter-Combinations-of-a-Phone-Number.java index def598a17..7d72b1866 100644 --- a/java/17-Letter-Combinations-of-a-Phone-Number.java +++ b/java/17-Letter-Combinations-of-a-Phone-Number.java @@ -3,35 +3,53 @@ import java.util.Map; class Solution { - private Map digitToChar = Map.of( - '2', "abc", '3', "def", '4', "ghi", '5', "jkl", - '6', "mno", '7', "pqrs", '8', "tuv", '9', "wxyz"); - - public List letterCombinations(String digits) { - - if (digits.length() == 0) { - return new ArrayList(); - } - - List ans = new ArrayList(); - String cur = ""; - backtrack(digits, ans, cur, 0); - return ans; - + + private Map digitToChar = Map.of( + '2', + "abc", + '3', + "def", + '4', + "ghi", + '5', + "jkl", + '6', + "mno", + '7', + "pqrs", + '8', + "tuv", + '9', + "wxyz" + ); + + public List letterCombinations(String digits) { + if (digits.length() == 0) { + return new ArrayList(); } - - public void backtrack(String digits, List ans, String cur, int index) { - - if (cur.length() == digits.length()) { - ans.add(cur); - return; - } else if (index >= digits.length()) { - return; - } else { - String digit = digitToChar.get(digits.charAt(index)); - for (char c : digit.toCharArray()) { - backtrack(digits, ans, cur + c, index + 1); - } - } + + List ans = new ArrayList(); + String cur = ""; + backtrack(digits, ans, cur, 0); + return ans; + } + + public void backtrack( + String digits, + List ans, + String cur, + int index + ) { + if (cur.length() == digits.length()) { + ans.add(cur); + return; + } else if (index >= digits.length()) { + return; + } else { + String digit = digitToChar.get(digits.charAt(index)); + for (char c : digit.toCharArray()) { + backtrack(digits, ans, cur + c, index + 1); + } } -} \ No newline at end of file + } +} diff --git a/java/187-Repeated-DNA-Sequences.java b/java/187-Repeated-DNA-Sequences.java index bdeecdc57..7260d8ca2 100644 --- a/java/187-Repeated-DNA-Sequences.java +++ b/java/187-Repeated-DNA-Sequences.java @@ -1,15 +1,17 @@ class Solution { - public List findRepeatedDnaSequences(String s) { - HashSet set = new HashSet<>(); - int start = 0; - HashSet ans = new HashSet<>(); - for (int end = 10; end<=s.length(); end++) { - if (set.contains(s.substring(start, end))) - ans.add(s.substring(start, end)); - set.add(s.substring(start, end)); - start++; - } - List list = new ArrayList<>(ans); - return list; + + public List findRepeatedDnaSequences(String s) { + HashSet set = new HashSet<>(); + int start = 0; + HashSet ans = new HashSet<>(); + for (int end = 10; end <= s.length(); end++) { + if (set.contains(s.substring(start, end))) ans.add( + s.substring(start, end) + ); + set.add(s.substring(start, end)); + start++; } + List list = new ArrayList<>(ans); + return list; + } } diff --git a/java/19-Remove-Nth-Node-From-End-of-List.java b/java/19-Remove-Nth-Node-From-End-of-List.java index d90eef421..fb6562cf7 100644 --- a/java/19-Remove-Nth-Node-From-End-of-List.java +++ b/java/19-Remove-Nth-Node-From-End-of-List.java @@ -15,28 +15,26 @@ // At that point we would have reached the (n-1)th node from the end using the pointer first // Unlink or Skip that node - class Solution { - public ListNode removeNthFromEnd(ListNode head, int n) { - - if (head == null || head.next == null) return null; - - ListNode temp = new ListNode(0); - temp.next = head; - ListNode first = temp, second = temp; - while (n > 0) { - second = second.next; - n--; - } + public ListNode removeNthFromEnd(ListNode head, int n) { + if (head == null || head.next == null) return null; - while (second.next != null) { - second = second.next; - first = first.next; - } + ListNode temp = new ListNode(0); + temp.next = head; + ListNode first = temp, second = temp; - first.next = first.next.next; - return temp.next; + while (n > 0) { + second = second.next; + n--; + } + while (second.next != null) { + second = second.next; + first = first.next; } + + first.next = first.next.next; + return temp.next; + } } diff --git a/java/190-Reverse-Bits.java b/java/190-Reverse-Bits.java index 1882031e7..4a7f20471 100644 --- a/java/190-Reverse-Bits.java +++ b/java/190-Reverse-Bits.java @@ -1,17 +1,18 @@ public class Solution { - // you need treat n as an unsigned value - public int reverseBits(int n) { - int res = 0; - int mask = 1; - - for (int i = 0; i < 32; i++) { - int tmp = n & mask; - if (tmp != 0) { - int tmpMask = 1 << (31 - i); - res = res | tmpMask; - } - mask <<= 1; - } - return res; + + // you need treat n as an unsigned value + public int reverseBits(int n) { + int res = 0; + int mask = 1; + + for (int i = 0; i < 32; i++) { + int tmp = n & mask; + if (tmp != 0) { + int tmpMask = 1 << (31 - i); + res = res | tmpMask; + } + mask <<= 1; } + return res; + } } diff --git a/java/191-Number-of-1-Bits.java b/java/191-Number-of-1-Bits.java index ac8a605c1..0d79719e3 100644 --- a/java/191-Number-of-1-Bits.java +++ b/java/191-Number-of-1-Bits.java @@ -1,28 +1,30 @@ //standard way public class Solution { - // you need to treat n as an unsigned value - public int hammingWeight(int n) { - int count = 0; - int mask = 1; - for (int i = 0; i < 32; i++) { - if ((n & mask) != 0) { - count++; - } - n >>= 1; - } - return count; + + // you need to treat n as an unsigned value + public int hammingWeight(int n) { + int count = 0; + int mask = 1; + for (int i = 0; i < 32; i++) { + if ((n & mask) != 0) { + count++; + } + n >>= 1; } + return count; + } } //smart way public class Solution { - // you need to treat n as an unsigned value - public int hammingWeight(int n) { - int count = 0; - while (n != 0) { - n = n & (n - 1); - count++; - } - return count; + + // you need to treat n as an unsigned value + public int hammingWeight(int n) { + int count = 0; + while (n != 0) { + n = n & (n - 1); + count++; } + return count; + } } diff --git a/java/198-House-Robber.java b/java/198-House-Robber.java index 349d1a706..c3e40b3a1 100644 --- a/java/198-House-Robber.java +++ b/java/198-House-Robber.java @@ -1,31 +1,35 @@ class Solution { - public int rob(int[] nums) { - if (nums == null || nums.length == 0) return 0; - if (nums.length == 1) return nums[0]; - if (nums.length == 2) return Math.max(nums[0], nums[1]); - - int robWithOutIncludingLastHouse = 0, robWithIncludingLastHouse = 0; - for (int n : nums) { - int temp = Math.max(robWithOutIncludingLastHouse + n, robWithIncludingLastHouse); - robWithOutIncludingLastHouse = robWithIncludingLastHouse; - robWithIncludingLastHouse = temp; - } - return robWithIncludingLastHouse; + public int rob(int[] nums) { + if (nums == null || nums.length == 0) return 0; + if (nums.length == 1) return nums[0]; + if (nums.length == 2) return Math.max(nums[0], nums[1]); + + int robWithOutIncludingLastHouse = 0, robWithIncludingLastHouse = 0; + + for (int n : nums) { + int temp = Math.max( + robWithOutIncludingLastHouse + n, + robWithIncludingLastHouse + ); + robWithOutIncludingLastHouse = robWithIncludingLastHouse; + robWithIncludingLastHouse = temp; } - - public int robDP(int[] nums) { - if (nums == null || nums.length == 0) return 0; - if (nums.length == 1) return nums[0]; - if (nums.length == 2) return Math.max(nums[0], nums[1]); - - int[] dp = new int[nums.length]; - dp[0] = nums[0]; - dp[1] = Math.max(nums[0], nums[1]); - - for (int i = 2; i < nums.length; i++) { - dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]); - } - return dp[nums.length - 1]; + return robWithIncludingLastHouse; + } + + public int robDP(int[] nums) { + if (nums == null || nums.length == 0) return 0; + if (nums.length == 1) return nums[0]; + if (nums.length == 2) return Math.max(nums[0], nums[1]); + + int[] dp = new int[nums.length]; + dp[0] = nums[0]; + dp[1] = Math.max(nums[0], nums[1]); + + for (int i = 2; i < nums.length; i++) { + dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]); } -} \ No newline at end of file + return dp[nums.length - 1]; + } +} diff --git a/java/199-Binary-Tree-Right-Side-View.java b/java/199-Binary-Tree-Right-Side-View.java index ab5c7f599..9ccb4842d 100644 --- a/java/199-Binary-Tree-Right-Side-View.java +++ b/java/199-Binary-Tree-Right-Side-View.java @@ -1,23 +1,23 @@ class Solution { - public List rightSideView(TreeNode root) { - List list = new ArrayList(); - if (root == null) return list; - bfs(list, root); - return list; + + public List rightSideView(TreeNode root) { + List list = new ArrayList(); + if (root == null) return list; + bfs(list, root); + return list; + } + + public void bfs(List list, TreeNode root) { + Queue q = new LinkedList<>(); + q.offer(root); + while (!q.isEmpty()) { + int levelSize = q.size(); + for (int i = 0; i < levelSize; i++) { + TreeNode cur = q.poll(); + if (i == 0) list.add(cur.val); + if (cur.right != null) q.offer(cur.right); + if (cur.left != null) q.offer(cur.left); + } } - - public void bfs(List list, TreeNode root) { - Queue q = new LinkedList<>(); - q.offer(root); - while (!q.isEmpty()) { - int levelSize = q.size(); - for (int i = 0; i0){ - ListNode newNode = new ListNode(q); - temp = head; - while(temp.next!=null){ - temp=temp.next; - } - temp.next = newNode; - newNode.next = null; - } - return head; - } -} \ No newline at end of file +/* + Name - Add Two Numbers + Link - https://leetcode.com/problems/add-two-numbers/ + Time Complexity - O(m + n) + Space Complexity - o(1) + Note - make use of modulo (get remainder) and division (get quotient) +*/ + +class Solution { + + public ListNode addTwoNumbers(ListNode first, ListNode second) { + int q = 0; + int r = 0; + int sum = 0; + ListNode head = null; + ListNode temp = null; + while (first != null || second != null) { + sum = + q + + ( + ((first != null) ? first.val : 0) + + ((second != null) ? second.val : 0) + ); + r = sum % 10; + q = sum / 10; + ListNode newNode = new ListNode(r); + if (head == null) { + head = newNode; + } else { + temp = head; + while (temp.next != null) { + temp = temp.next; + } + temp.next = newNode; + newNode.next = null; + } + if (first != null) { + first = first.next; + } + if (second != null) { + second = second.next; + } + } + if (q > 0) { + ListNode newNode = new ListNode(q); + temp = head; + while (temp.next != null) { + temp = temp.next; + } + temp.next = newNode; + newNode.next = null; + } + return head; + } +} diff --git a/java/20-Valid-Parentheses.java b/java/20-Valid-Parentheses.java index c887f6a5c..fb1028e29 100644 --- a/java/20-Valid-Parentheses.java +++ b/java/20-Valid-Parentheses.java @@ -1,21 +1,22 @@ class Solution { - public boolean isValid(String s) { - if (s.length()%2!=0) - return false; - Stack stack = new Stack<>(); - for (int i = 0; i stack = new Stack<>(); + for (int i = 0; i < s.length(); i++) { + if ( + stack.isEmpty() && + (s.charAt(i) == ')' || s.charAt(i) == '}' || s.charAt(i) == ']') + ) return false; else { + if (!stack.isEmpty()) { + if (stack.peek() == '(' && s.charAt(i) == ')') stack.pop(); else if ( + stack.peek() == '{' && s.charAt(i) == '}' + ) stack.pop(); else if ( + stack.peek() == '[' && s.charAt(i) == ']' + ) stack.pop(); else stack.add(s.charAt(i)); + } else stack.add(s.charAt(i)); + } } + return stack.isEmpty(); + } } diff --git a/java/200-Number-of-Islands.java b/java/200-Number-of-Islands.java index 8239217dd..72e59c03f 100644 --- a/java/200-Number-of-Islands.java +++ b/java/200-Number-of-Islands.java @@ -1,25 +1,32 @@ class Solution { - public int numIslands(char[][] grid) { - int count = 0; - for (int i = 0; i= grid.length || j>=grid[0].length || grid[i][j]=='0') { - return; - } - grid[i][j] = '0'; - dfs(grid, i+1, j); - dfs(grid, i, j+1); - dfs(grid, i-1, j); - dfs(grid, i, j-1); + return count; + } + + public void dfs(char[][] grid, int i, int j) { + if ( + i < 0 || + j < 0 || + i >= grid.length || + j >= grid[0].length || + grid[i][j] == '0' + ) { + return; } + grid[i][j] = '0'; + dfs(grid, i + 1, j); + dfs(grid, i, j + 1); + dfs(grid, i - 1, j); + dfs(grid, i, j - 1); + } } diff --git a/java/202-Happy-Number.java b/java/202-Happy-Number.java index d0a970c14..ed3ef318c 100644 --- a/java/202-Happy-Number.java +++ b/java/202-Happy-Number.java @@ -1,41 +1,34 @@ class Solution { - public boolean isHappy(int n) { - - if (n == 1 || n == -1) { - return true; - } - - Set visit = new HashSet(); - - // compute square until getting duplicate value - while (!visit.contains(n)) { - visit.add(n); - // using helper function to compute the sum of squares - n = sumOfSquare(n); - - if (n == 1) - return true; - - } - - return false; + public boolean isHappy(int n) { + if (n == 1 || n == -1) { + return true; } - public int sumOfSquare(int n) { + Set visit = new HashSet(); - int output = 0; + // compute square until getting duplicate value + while (!visit.contains(n)) { + visit.add(n); + // using helper function to compute the sum of squares + n = sumOfSquare(n); - while (n != 0) { - int digit = n % 10; - digit = digit * digit; - output += digit; - n = n / 10; + if (n == 1) return true; + } - } + return false; + } - return output; + public int sumOfSquare(int n) { + int output = 0; + while (n != 0) { + int digit = n % 10; + digit = digit * digit; + output += digit; + n = n / 10; } -} \ No newline at end of file + return output; + } +} diff --git a/java/206. Reverse Linked List.java b/java/206. Reverse Linked List.java index fc36e0995..3285f7cc9 100644 --- a/java/206. Reverse Linked List.java +++ b/java/206. Reverse Linked List.java @@ -1,32 +1,32 @@ //Use three pointers and so you can change the next of the mid to the first one without losing the track of the original left. //Iterative version class Solution { - public ListNode reverseList(ListNode head) { - ListNode p = null; - ListNode q = null; - ListNode r = head; - while (r!=null) { - p = q; - q = r; - r = r.next; - q.next = p; - } - return q; + + public ListNode reverseList(ListNode head) { + ListNode p = null; + ListNode q = null; + ListNode r = head; + while (r != null) { + p = q; + q = r; + r = r.next; + q.next = p; } + return q; + } } //Recursive version class Solution { - public ListNode reverseList(ListNode head) { - return rev(head, null); - } - - public ListNode rev(ListNode node, ListNode pre) { - if (node == null) - return pre; - ListNode temp = node.next; - node.next = pre; - return rev(temp, node); - } - + + public ListNode reverseList(ListNode head) { + return rev(head, null); + } + + public ListNode rev(ListNode node, ListNode pre) { + if (node == null) return pre; + ListNode temp = node.next; + node.next = pre; + return rev(temp, node); + } } diff --git a/java/207-Course-Schedule.java b/java/207-Course-Schedule.java index 3f82d707b..b127d72fc 100644 --- a/java/207-Course-Schedule.java +++ b/java/207-Course-Schedule.java @@ -1,39 +1,40 @@ class Solution { - public boolean canFinish(int numCourses, int[][] prerequisites) { - List> adj = new ArrayList<>(); - for (int i = 0; i < numCourses; i++) { - adj.add(new ArrayList<>()); - } - - for (int i = 0; i < prerequisites.length; i++) { - adj.get(prerequisites[i][0]).add(prerequisites[i][1]); - } - - int[] visited = new int[numCourses]; - for (int i = 0; i < numCourses; i++) { - if (visited[i] == 0) { - if (isCyclic(adj, visited, i)) { - return false; - } - } - } - return true; + + public boolean canFinish(int numCourses, int[][] prerequisites) { + List> adj = new ArrayList<>(); + for (int i = 0; i < numCourses; i++) { + adj.add(new ArrayList<>()); } - - private boolean isCyclic(List> adj, int[] visited, int curr) { - if (visited[curr] == 2) { - return true; + + for (int i = 0; i < prerequisites.length; i++) { + adj.get(prerequisites[i][0]).add(prerequisites[i][1]); + } + + int[] visited = new int[numCourses]; + for (int i = 0; i < numCourses; i++) { + if (visited[i] == 0) { + if (isCyclic(adj, visited, i)) { + return false; } - - visited[curr] = 2; - for (int i = 0; i < adj.get(curr).size(); i++) { - if (visited[adj.get(curr).get(i)] != 1) { - if (isCyclic(adj, visited, adj.get(curr).get(i))) { - return true; - } - } + } + } + return true; + } + + private boolean isCyclic(List> adj, int[] visited, int curr) { + if (visited[curr] == 2) { + return true; + } + + visited[curr] = 2; + for (int i = 0; i < adj.get(curr).size(); i++) { + if (visited[adj.get(curr).get(i)] != 1) { + if (isCyclic(adj, visited, adj.get(curr).get(i))) { + return true; } - visited[curr] = 1; - return false; + } } + visited[curr] = 1; + return false; + } } diff --git a/java/208-Implement-Trie-Prefix-Tree.java b/java/208-Implement-Trie-Prefix-Tree.java index 1f68fb540..85c1f41c1 100644 --- a/java/208-Implement-Trie-Prefix-Tree.java +++ b/java/208-Implement-Trie-Prefix-Tree.java @@ -1,54 +1,56 @@ class Trie { - Node root; - public Trie() { - root = new Node('\0'); //dummy node - } + Node root; - public void insert(String word) { - Node curr = root; - for (char x : word.toCharArray()) { - if (curr.children[x - 'a'] == null) { - curr.children[x - 'a'] = new Node(x); - } - curr = curr.children[x - 'a']; - } - curr.isWord = true; - } + public Trie() { + root = new Node('\0'); //dummy node + } - public boolean search(String word) { - Node res = getLast(word); - return (res != null && res.isWord); + public void insert(String word) { + Node curr = root; + for (char x : word.toCharArray()) { + if (curr.children[x - 'a'] == null) { + curr.children[x - 'a'] = new Node(x); + } + curr = curr.children[x - 'a']; } - - //helper method - public Node getLast(String word) { - Node curr = root; - for (char x : word.toCharArray()) { - if (curr.children[x - 'a'] == null) { - return null; - } - - curr = curr.children[x - 'a']; - } - return curr; + curr.isWord = true; + } + + public boolean search(String word) { + Node res = getLast(word); + return (res != null && res.isWord); + } + + //helper method + public Node getLast(String word) { + Node curr = root; + for (char x : word.toCharArray()) { + if (curr.children[x - 'a'] == null) { + return null; + } + + curr = curr.children[x - 'a']; } + return curr; + } - public boolean startsWith(String prefix) { - Node res = getLast(prefix); - if (res == null) return false; - return true; - } + public boolean startsWith(String prefix) { + Node res = getLast(prefix); + if (res == null) return false; + return true; + } + + class Node { - class Node { - private char value; - private boolean isWord; - private Node[] children; + private char value; + private boolean isWord; + private Node[] children; - public Node(char val) { - this.value = val; - this.isWord = false; - this.children = new Node[26]; - } + public Node(char val) { + this.value = val; + this.isWord = false; + this.children = new Node[26]; } + } } diff --git a/java/21-Merge-Two-Sorted-Lists.java b/java/21-Merge-Two-Sorted-Lists.java index 9c713b1f1..2c3554d3b 100644 --- a/java/21-Merge-Two-Sorted-Lists.java +++ b/java/21-Merge-Two-Sorted-Lists.java @@ -11,22 +11,23 @@ * } */ class Solution { - public ListNode mergeTwoLists(ListNode list1, ListNode list2) { - final ListNode root = new ListNode(); - ListNode prev = root; - while (list1 != null && list2 != null) { - if(list1.val < list2.val) { - prev.next = list1; - list1 = list1.next; - } else { - prev.next = list2; - list2 = list2.next; - } - prev = prev.next; - } - prev.next = list1 != null ? list1 : list2; - return root.next; + + public ListNode mergeTwoLists(ListNode list1, ListNode list2) { + final ListNode root = new ListNode(); + ListNode prev = root; + while (list1 != null && list2 != null) { + if (list1.val < list2.val) { + prev.next = list1; + list1 = list1.next; + } else { + prev.next = list2; + list2 = list2.next; + } + prev = prev.next; } + prev.next = list1 != null ? list1 : list2; + return root.next; + } } // Solution using Recursion @@ -41,21 +42,22 @@ public ListNode mergeTwoLists(ListNode list1, ListNode list2) { * } */ class Solution { - public ListNode mergeTwoLists(ListNode list1, ListNode list2) { - ListNode head = new ListNode(0); - if(list1 == null && list2 == null) return null; - if(list1 == null) return list2; - if(list2 == null) return list1; + public ListNode mergeTwoLists(ListNode list1, ListNode list2) { + ListNode head = new ListNode(0); + + if (list1 == null && list2 == null) return null; + if (list1 == null) return list2; + if (list2 == null) return list1; - if(list1.val > list2.val) { - head = list2; - list2 = list2.next; - } else { - head = list1; - list1 = list1.next; - } - head.next = mergeTwoLists(list1, list2); - return head; + if (list1.val > list2.val) { + head = list2; + list2 = list2.next; + } else { + head = list1; + list1 = list1.next; } + head.next = mergeTwoLists(list1, list2); + return head; + } } diff --git a/java/210-Course-Schedule-II.java b/java/210-Course-Schedule-II.java index 4ffdc1bf6..a7aa54a2c 100644 --- a/java/210-Course-Schedule-II.java +++ b/java/210-Course-Schedule-II.java @@ -1,48 +1,48 @@ class Solution { - public int[] findOrder(int numCourses, int[][] prerequisites) { - Map> adjList = new HashMap>(); - int[] indegree = new int[numCourses]; - int[] topologicalOrder = new int[numCourses]; - - //creating the adjlist - for (int i = 0; i < prerequisites.length; i++) { - int post = prerequisites[i][0]; - int pre = prerequisites[i][1]; - List lst = adjList.getOrDefault(pre, new ArrayList()); - lst.add(post); - adjList.put(pre, lst); - - indegree[post] += 1; - } - - Queue q = new LinkedList(); - for (int i = 0; i < numCourses; i++) { - if (indegree[i] == 0) { - q.add(i); - } - } + public int[] findOrder(int numCourses, int[][] prerequisites) { + Map> adjList = new HashMap>(); + int[] indegree = new int[numCourses]; + int[] topologicalOrder = new int[numCourses]; + + //creating the adjlist + for (int i = 0; i < prerequisites.length; i++) { + int post = prerequisites[i][0]; + int pre = prerequisites[i][1]; + List lst = adjList.getOrDefault(pre, new ArrayList()); + lst.add(post); + adjList.put(pre, lst); + + indegree[post] += 1; + } - int i = 0; - while (!q.isEmpty()) { - int node = q.remove(); - topologicalOrder[i++] = node; + Queue q = new LinkedList(); + for (int i = 0; i < numCourses; i++) { + if (indegree[i] == 0) { + q.add(i); + } + } - if (adjList.containsKey(node)) { - for (Integer neighbor : adjList.get(node)) { - indegree[neighbor]--; + int i = 0; + while (!q.isEmpty()) { + int node = q.remove(); + topologicalOrder[i++] = node; - if (indegree[neighbor] == 0) { - q.add(neighbor); - } - } - } - } + if (adjList.containsKey(node)) { + for (Integer neighbor : adjList.get(node)) { + indegree[neighbor]--; - if (i == numCourses) { - return topologicalOrder; + if (indegree[neighbor] == 0) { + q.add(neighbor); + } } + } + } - return new int[0]; + if (i == numCourses) { + return topologicalOrder; } + + return new int[0]; + } } diff --git a/java/213-House-RobberII.java b/java/213-House-RobberII.java index b87bdc1d9..9f151f32d 100644 --- a/java/213-House-RobberII.java +++ b/java/213-House-RobberII.java @@ -1,20 +1,23 @@ class Solution { - public int rob(int[] nums) { - - - if(nums.length == 0 ) return 0; - if(nums.length == 1 ) return nums[0]; - - return Math.max(robHelper(nums,0,nums.length - 2) , robHelper(nums , 1 , nums.length - 1)); + + public int rob(int[] nums) { + if (nums.length == 0) return 0; + if (nums.length == 1) return nums[0]; + + return Math.max( + robHelper(nums, 0, nums.length - 2), + robHelper(nums, 1, nums.length - 1) + ); + } + + public int robHelper(int[] nums, int start, int end) { + int rob1 = 0; + int rob2 = 0; + for (int i = start; i <= end; i++) { + int temp = Math.max(rob1 + nums[i], rob2); + rob1 = rob2; + rob2 = temp; } - public int robHelper(int[] nums , int start , int end){ - int rob1 = 0; - int rob2 = 0; - for (int i = start; i <= end; i++) { - int temp = Math.max(rob1 + nums[i], rob2); - rob1 = rob2; - rob2 = temp; - } - return rob2; - } -} \ No newline at end of file + return rob2; + } +} diff --git a/java/215-Kth-Largest-Element-in-an-Array.java b/java/215-Kth-Largest-Element-in-an-Array.java index f75ae35bb..a31ee5a3e 100644 --- a/java/215-Kth-Largest-Element-in-an-Array.java +++ b/java/215-Kth-Largest-Element-in-an-Array.java @@ -1,19 +1,20 @@ class Solution { - public int findKthLargest(int[] nums, int k) { - //create a min heap - PriorityQueue heap = new PriorityQueue(); - - //iterate over the array - for(int n: nums){ - //first add the integer to heap - heap.add(n); - //if size of the heap is greater than k - if(heap.size() > k){ - //remove the root element (lowest of all) - heap.poll(); - } - } - //finally heap has k largest elements left with root as the kth largest element - return heap.peek(); + + public int findKthLargest(int[] nums, int k) { + //create a min heap + PriorityQueue heap = new PriorityQueue(); + + //iterate over the array + for (int n : nums) { + //first add the integer to heap + heap.add(n); + //if size of the heap is greater than k + if (heap.size() > k) { + //remove the root element (lowest of all) + heap.poll(); + } } + //finally heap has k largest elements left with root as the kth largest element + return heap.peek(); + } } diff --git a/java/217-Contains-Duplicate.java b/java/217-Contains-Duplicate.java index e09c1d4b6..c42099416 100644 --- a/java/217-Contains-Duplicate.java +++ b/java/217-Contains-Duplicate.java @@ -1,12 +1,13 @@ class Solution { - public boolean containsDuplicate(int[] nums) { - Set uniques = new HashSet<>(); - for (int i = 0; i < nums.length; i++) { - if (uniques.contains(nums[i])) { - return true; - } - uniques.add(nums[i]); - } - return false; + + public boolean containsDuplicate(int[] nums) { + Set uniques = new HashSet<>(); + for (int i = 0; i < nums.length; i++) { + if (uniques.contains(nums[i])) { + return true; + } + uniques.add(nums[i]); } + return false; + } } diff --git a/java/22-Generate-Parentheses.java b/java/22-Generate-Parentheses.java index 4a9ad516b..7793dc831 100644 --- a/java/22-Generate-Parentheses.java +++ b/java/22-Generate-Parentheses.java @@ -1,45 +1,43 @@ package arrays; + import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Stack; - public class Solution { - public static void main(String[] args) { - Solution sol=new Solution(); - sol.generateParenthesis(3); + public static void main(String[] args) { + Solution sol = new Solution(); + sol.generateParenthesis(3); + } + + Stack stack = new Stack<>(); + List res = new ArrayList<>(); + + public List generateParenthesis(int n) { + backtrack(0, 0, n); + return res; + } + + private void backtrack(int openN, int closedN, int n) { + if (openN == closedN && closedN == n) { + Iterator vale = stack.iterator(); + String temp = ""; + while (vale.hasNext()) { + temp = temp + vale.next(); + } + res.add(temp); } - - Stack stack=new Stack<>(); - List res=new ArrayList<>(); - public List generateParenthesis(int n) { - - backtrack(0,0,n); - return res; + if (openN < n) { + stack.push('('); + backtrack(openN + 1, closedN, n); + stack.pop(); } - - private void backtrack(int openN, int closedN,int n) { - if(openN==closedN && closedN==n){ - Iterator vale= stack.iterator(); - String temp=""; - while(vale.hasNext()){ - temp=temp+vale.next(); - } - res.add(temp); - } - if(openN minHeap = new PriorityQueue<>(); - - for(ListNode nodes : lists){ - ListNode current = nodes; - while(current != null){ - minHeap.add(current.val); - current = current.next; - } - } - - ListNode dummy = new ListNode(0); - ListNode current = dummy; - - while(!minHeap.isEmpty()){ - current.next = new ListNode(minHeap.poll()); - current = current.next; - } - - return dummy.next; + + public ListNode mergeKLists(ListNode[] lists) { + Queue minHeap = new PriorityQueue<>(); + + for (ListNode nodes : lists) { + ListNode current = nodes; + while (current != null) { + minHeap.add(current.val); + current = current.next; + } } + + ListNode dummy = new ListNode(0); + ListNode current = dummy; + + while (!minHeap.isEmpty()) { + current.next = new ListNode(minHeap.poll()); + current = current.next; + } + + return dummy.next; + } } diff --git a/java/230-Kth-Smallest-Element-in-a-BST.java b/java/230-Kth-Smallest-Element-in-a-BST.java index 8be39877f..4f75e787c 100644 --- a/java/230-Kth-Smallest-Element-in-a-BST.java +++ b/java/230-Kth-Smallest-Element-in-a-BST.java @@ -14,17 +14,18 @@ * } */ class Solution { - public int kthSmallest(TreeNode root, int k) { - List list = new ArrayList<>(); - inorder(root, list); - return list.get(k - 1); - } - - private void inorder(TreeNode root, List list) { - if (root == null) return; - - inorder(root.left, list); - list.add(root.val); - inorder(root.right, list); - } + + public int kthSmallest(TreeNode root, int k) { + List list = new ArrayList<>(); + inorder(root, list); + return list.get(k - 1); + } + + private void inorder(TreeNode root, List list) { + if (root == null) return; + + inorder(root.left, list); + list.add(root.val); + inorder(root.right, list); + } } diff --git a/java/2309.-Greatest-English-Letter-in-Upper-and-Lower-Case.java b/java/2309.-Greatest-English-Letter-in-Upper-and-Lower-Case.java index d469b5198..3ecdb6f5c 100644 --- a/java/2309.-Greatest-English-Letter-in-Upper-and-Lower-Case.java +++ b/java/2309.-Greatest-English-Letter-in-Upper-and-Lower-Case.java @@ -1,13 +1,15 @@ //Contest 298 brute-force feel free to share any improvements class Solution { - public String greatestLetter(String s) { - HashSet set = new HashSet<>(); - int ans = -1; - for (int i = 0; i set = new HashSet<>(); + int ans = -1; + for (int i = 0; i < s.length(); i++) { + if ( + set.contains((s.charAt(i) - 32)) || set.contains((s.charAt(i) + 32)) + ) ans = Math.max(ans, (int) Character.toUpperCase(s.charAt(i))); + set.add(0 + s.charAt(i)); } + return ans == -1 ? "" : (char) ans + ""; + } } diff --git a/java/2310-Sum-of-Numbers-With-Units-Digit-K.java b/java/2310-Sum-of-Numbers-With-Units-Digit-K.java index 7b1dad817..62dc66f4e 100644 --- a/java/2310-Sum-of-Numbers-With-Units-Digit-K.java +++ b/java/2310-Sum-of-Numbers-With-Units-Digit-K.java @@ -1,18 +1,20 @@ //Contest 298 problem brute-force. Feel free to update this. class Solution { - public int minimumNumbers(int num, int k) { - if (num == 0) return 0; - if (num%10 == k) return 1; - if (k == 0 && num%10 == 0) return 1; - else if (k==0 && num%10!=0) return -1; - int temp = num; - num -= k; - int len = 1; - while (num>0) { - len++; - if (num%10 == k) return len; - num -= k; - } - return num<0?-1:len; + + public int minimumNumbers(int num, int k) { + if (num == 0) return 0; + if (num % 10 == k) return 1; + if (k == 0 && num % 10 == 0) return 1; else if ( + k == 0 && num % 10 != 0 + ) return -1; + int temp = num; + num -= k; + int len = 1; + while (num > 0) { + len++; + if (num % 10 == k) return len; + num -= k; } + return num < 0 ? -1 : len; + } } diff --git a/java/2328-Number-of-Increasing-Paths-in-a-Grid.java b/java/2328-Number-of-Increasing-Paths-in-a-Grid.java index cfb1b616a..03a06ceec 100644 --- a/java/2328-Number-of-Increasing-Paths-in-a-Grid.java +++ b/java/2328-Number-of-Increasing-Paths-in-a-Grid.java @@ -1,37 +1,45 @@ //Exactly similar to : 329. Longest Increasing Path in a Matrix class Solution { - long mod = (long)Math.pow(10,9)+7; - public int countPaths(int[][] grid) { - int m = grid.length, n = grid[0].length; - long[][] dp = new long[m][n]; - for (int i = 0; i=m || j>=n || prevValue>=grid[i][j]) - return 0; - if (dp[i][j]!=0) - return dp[i][j]; - prevValue = grid[i][j]; - long left = dfs(grid, dp, i, j-1, m, n, prevValue)%mod; - long bottom = dfs(grid, dp, i+1, j, m, n, prevValue)%mod; - long right = dfs(grid, dp, i, j+1, m, n, prevValue)%mod; - long top = dfs(grid, dp, i-1, j, m, n, prevValue)%mod; - dp[i][j] = (1+left+top+bottom+right)%mod; - return dp[i][j]; + long sum = 0; + for (long[] d : dp) { + for (long i : d) { + sum = (sum + i) % mod; + } } + return (int) sum; + } + + public long dfs( + int[][] grid, + long[][] dp, + int i, + int j, + int m, + int n, + int prevValue + ) { + if (i < 0 || j < 0 || i >= m || j >= n || prevValue >= grid[i][j]) return 0; + if (dp[i][j] != 0) return dp[i][j]; + prevValue = grid[i][j]; + long left = dfs(grid, dp, i, j - 1, m, n, prevValue) % mod; + long bottom = dfs(grid, dp, i + 1, j, m, n, prevValue) % mod; + long right = dfs(grid, dp, i, j + 1, m, n, prevValue) % mod; + long top = dfs(grid, dp, i - 1, j, m, n, prevValue) % mod; + dp[i][j] = (1 + left + top + bottom + right) % mod; + return dp[i][j]; + } } diff --git a/java/234. Palindrome Linked List.java b/java/234. Palindrome Linked List.java index ee8eef2b1..9fd2dc292 100644 --- a/java/234. Palindrome Linked List.java +++ b/java/234. Palindrome Linked List.java @@ -3,34 +3,33 @@ //It'll automatically take care of the edge cases of odd and even class Solution { - public boolean isPalindrome(ListNode head) { - ListNode fast = head; - ListNode slow = head; - while (fast !=null && fast.next !=null) { - fast = fast.next.next; - slow = slow.next; - } - ListNode temp = reverse(slow); - while (temp!=null && head!=null) { - if (temp.val != head.val) - return false; - temp = temp.next; - head = head.next; - } - return true; + + public boolean isPalindrome(ListNode head) { + ListNode fast = head; + ListNode slow = head; + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + } + ListNode temp = reverse(slow); + while (temp != null && head != null) { + if (temp.val != head.val) return false; + temp = temp.next; + head = head.next; } - - public ListNode reverse(ListNode head) { - ListNode p = null; - ListNode q = null; - ListNode r = head; - while (r!=null) { - p = q; - q = r; - r = r.next; - q.next = p; - } - return q; + return true; + } + + public ListNode reverse(ListNode head) { + ListNode p = null; + ListNode q = null; + ListNode r = head; + while (r != null) { + p = q; + q = r; + r = r.next; + q.next = p; } - + return q; + } } diff --git a/java/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.java b/java/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.java index 704497f3a..2e6e7d7d6 100644 --- a/java/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.java +++ b/java/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.java @@ -9,9 +9,18 @@ */ class Solution { - public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { - if (p.val > root.val && q.val > root.val) return lowestCommonAncestor(root.right, p, q); - if (p.val < root.val && q.val < root.val) return lowestCommonAncestor(root.left, p, q); - return root; - } + + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (p.val > root.val && q.val > root.val) return lowestCommonAncestor( + root.right, + p, + q + ); + if (p.val < root.val && q.val < root.val) return lowestCommonAncestor( + root.left, + p, + q + ); + return root; + } } diff --git a/java/236-Lowest-Common-Ancestor-of-a-Binary-Tree.java b/java/236-Lowest-Common-Ancestor-of-a-Binary-Tree.java index e2d872e8a..242714699 100644 --- a/java/236-Lowest-Common-Ancestor-of-a-Binary-Tree.java +++ b/java/236-Lowest-Common-Ancestor-of-a-Binary-Tree.java @@ -1,14 +1,13 @@ class Solution { - public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { - if(root==null) return null; - if((root.val==p.val || root.val==q.val))return root; - TreeNode left=lowestCommonAncestor(root.left,p,q); - TreeNode right=lowestCommonAncestor(root.right,p,q); - - if(left!=null&&right!=null){return root;} - else if(left!=null)return left; - else return right; - - } - + + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root == null) return null; + if ((root.val == p.val || root.val == q.val)) return root; + TreeNode left = lowestCommonAncestor(root.left, p, q); + TreeNode right = lowestCommonAncestor(root.right, p, q); + + if (left != null && right != null) { + return root; + } else if (left != null) return left; else return right; + } } diff --git a/java/238-Product-of-Array-Except-Self.java b/java/238-Product-of-Array-Except-Self.java index b678d6dc8..51113d3d2 100644 --- a/java/238-Product-of-Array-Except-Self.java +++ b/java/238-Product-of-Array-Except-Self.java @@ -2,22 +2,23 @@ //This one is constant space because we are returning the array we created class Solution { - public int[] productExceptSelf(int[] nums) { - int[] arr = new int[nums.length]; - arr[0] = 1; - for (int i = 1; i=0; i--) { - int store = nums[i]; - nums[i] = nums[i+1]*prod; - prod = store; - } - for (int i = 0; i= 0; i--) { + int store = nums[i]; + nums[i] = nums[i + 1] * prod; + prod = store; + } + for (int i = 0; i < nums.length; i++) { + arr[i] = arr[i] * nums[i]; } + return arr; + } } diff --git a/java/239-Sliding-Window-Maximum.java b/java/239-Sliding-Window-Maximum.java index 4c724743a..dcd9033dd 100644 --- a/java/239-Sliding-Window-Maximum.java +++ b/java/239-Sliding-Window-Maximum.java @@ -1,17 +1,15 @@ class Solution { - public int[] maxSlidingWindow(int[] nums, int k) { - int[] ans = new int[nums.length-k+1]; - int j = 0; - Deque q = new LinkedList<>(); - for (int i = 0; inums[q.peekLast()]) - q.pollLast(); - q.offer(i); - if (i>=k-1) - ans[j++] = nums[q.peekFirst()]; - } - return ans; + + public int[] maxSlidingWindow(int[] nums, int k) { + int[] ans = new int[nums.length - k + 1]; + int j = 0; + Deque q = new LinkedList<>(); + for (int i = 0; i < nums.length; i++) { + if (!q.isEmpty() && q.peekFirst() < i - k + 1) q.pollFirst(); + while (!q.isEmpty() && nums[i] > nums[q.peekLast()]) q.pollLast(); + q.offer(i); + if (i >= k - 1) ans[j++] = nums[q.peekFirst()]; } + return ans; + } } diff --git a/java/24 Swap Nodes in Pairs.java b/java/24 Swap Nodes in Pairs.java index f029e6c97..1ab78cde8 100644 --- a/java/24 Swap Nodes in Pairs.java +++ b/java/24 Swap Nodes in Pairs.java @@ -1,31 +1,31 @@ //Iterative version class Solution { - public ListNode swapPairs(ListNode head) { - if (head == null || head.next == null) return head; - ListNode dummy = new ListNode(0); - dummy.next = head; - ListNode temp = dummy; - while (temp.next!=null && temp.next.next!=null) { - ListNode first = temp.next; - ListNode second = temp.next.next; - temp.next = second; - first.next = second.next; - second.next = first; - temp = first; - } - return dummy.next; - + + public ListNode swapPairs(ListNode head) { + if (head == null || head.next == null) return head; + ListNode dummy = new ListNode(0); + dummy.next = head; + ListNode temp = dummy; + while (temp.next != null && temp.next.next != null) { + ListNode first = temp.next; + ListNode second = temp.next.next; + temp.next = second; + first.next = second.next; + second.next = first; + temp = first; } + return dummy.next; + } } //Recursive version class Solution { - public ListNode swapPairs(ListNode head) { - if (head == null || head.next == null) - return head; - ListNode p = head.next; - head.next = swapPairs(head.next.next); - p.next = head; - return p; - } + + public ListNode swapPairs(ListNode head) { + if (head == null || head.next == null) return head; + ListNode p = head.next; + head.next = swapPairs(head.next.next); + p.next = head; + return p; + } } diff --git a/java/242-Valid-Anagram.java b/java/242-Valid-Anagram.java index d189aadd8..fb28f9dbe 100644 --- a/java/242-Valid-Anagram.java +++ b/java/242-Valid-Anagram.java @@ -1,18 +1,17 @@ class Solution { - public boolean isAnagram(String s, String t) { - if(s.length() != t.length()) return false; - int[] store = new int[26]; + public boolean isAnagram(String s, String t) { + if (s.length() != t.length()) return false; - for(int i=0; i0) { - ListNode temp = head.next; - head.next = cur; - cur = head; - head = temp; - } - head = cur; - } - return head; + + public ListNode reverseKGroup(ListNode head, int k) { + ListNode cur = head; + int count = 0; + while (cur != null && count != k) { + cur = cur.next; + count++; + } + if (count == k) { + cur = reverseKGroup(cur, k); + while (count-- > 0) { + ListNode temp = head.next; + head.next = cur; + cur = head; + head = temp; + } + head = cur; } + return head; + } } - - diff --git a/java/252-Meeting-Rooms.java b/java/252-Meeting-Rooms.java index de2585775..00ecf62ae 100644 --- a/java/252-Meeting-Rooms.java +++ b/java/252-Meeting-Rooms.java @@ -10,31 +10,32 @@ */ public class Solution { - /** - * @param intervals: an array of meeting time intervals - * @return: if a person could attend all meetings - */ - public boolean canAttendMeetings(List intervals) { - int length = intervals.size(); - if (intervals.size() == 0 || length == 1) return true; - // Write your code here - int[] start = new int[length]; - int[] end = new int[length]; - for (int i = 0; i < length; i++) { - start[i] = intervals.get(i).start; - end[i] = intervals.get(i).end; - } + /** + * @param intervals: an array of meeting time intervals + * @return: if a person could attend all meetings + */ + public boolean canAttendMeetings(List intervals) { + int length = intervals.size(); + if (intervals.size() == 0 || length == 1) return true; + // Write your code here - Arrays.sort(start); - Arrays.sort(end); + int[] start = new int[length]; + int[] end = new int[length]; + for (int i = 0; i < length; i++) { + start[i] = intervals.get(i).start; + end[i] = intervals.get(i).end; + } - int j = 0; - while (j + 1 < length) { - if (end[j] > start[j + 1]) return false; - j++; - } + Arrays.sort(start); + Arrays.sort(end); - return true; + int j = 0; + while (j + 1 < length) { + if (end[j] > start[j + 1]) return false; + j++; } + + return true; + } } diff --git a/java/253-Meeting-Rooms-ii.java b/java/253-Meeting-Rooms-ii.java index 0a512be06..0ea0f2540 100644 --- a/java/253-Meeting-Rooms-ii.java +++ b/java/253-Meeting-Rooms-ii.java @@ -10,25 +10,29 @@ */ public class Solution { - /** - * @param intervals: an array of meeting time intervals - * @return: the minimum number of conference rooms required - */ - public int minMeetingRooms(List intervals) { - if(intervals.isEmpty()) return 0; - Collections.sort(intervals, (a, b) -> Integer.compare(a.start, b.start)); + /** + * @param intervals: an array of meeting time intervals + * @return: the minimum number of conference rooms required + */ + public int minMeetingRooms(List intervals) { + if (intervals.isEmpty()) return 0; - Queue queue = new PriorityQueue<>((a, b) -> Integer.compare(a.end, b.end)); - - int count = 0; - for (Interval interval : intervals) { - - while(!queue.isEmpty() && interval.start >= queue.peek().end) queue.poll(); + Collections.sort(intervals, (a, b) -> Integer.compare(a.start, b.start)); - queue.offer(interval); - count = Math.max(count, queue.size()); - } - return count; + Queue queue = new PriorityQueue<>((a, b) -> + Integer.compare(a.end, b.end) + ); + + int count = 0; + for (Interval interval : intervals) { + while ( + !queue.isEmpty() && interval.start >= queue.peek().end + ) queue.poll(); + + queue.offer(interval); + count = Math.max(count, queue.size()); } + return count; + } } diff --git a/java/261-Graph-Valid-Tree.java b/java/261-Graph-Valid-Tree.java index 0342e81ed..fd438c0c6 100644 --- a/java/261-Graph-Valid-Tree.java +++ b/java/261-Graph-Valid-Tree.java @@ -1,40 +1,41 @@ public class Solution { - private Map> adjacencyList = new HashMap<>(); + private Map> adjacencyList = new HashMap<>(); - public boolean validTree(int n, int[][] edges) { - if (n == 0 || n == 1) return true; + public boolean validTree(int n, int[][] edges) { + if (n == 0 || n == 1) return true; - if (edges.length == 0) return false; + if (edges.length == 0) return false; - for (var edge: edges) { - var node1 = edge[0]; - var node2 = edge[1]; - adjacencyList.putIfAbsent(node1, new ArrayList<>()); - adjacencyList.putIfAbsent(node2, new ArrayList<>()); - adjacencyList.get(node1).add(node2); - adjacencyList.get(node2).add(node1); - } - - Set visited = new HashSet<>(); - - return depthFirstSearch(0, -1, visited) && visited.size() == n; + for (var edge : edges) { + var node1 = edge[0]; + var node2 = edge[1]; + adjacencyList.putIfAbsent(node1, new ArrayList<>()); + adjacencyList.putIfAbsent(node2, new ArrayList<>()); + adjacencyList.get(node1).add(node2); + adjacencyList.get(node2).add(node1); } - private boolean depthFirstSearch(int node, int previous, Set visited) { - if (visited.contains(node)) - return false; + Set visited = new HashSet<>(); - visited.add(node); + return depthFirstSearch(0, -1, visited) && visited.size() == n; + } - for (var neighbor: adjacencyList.get(node)) { - if (neighbor == previous) - continue; + private boolean depthFirstSearch( + int node, + int previous, + Set visited + ) { + if (visited.contains(node)) return false; - if (!depthFirstSearch(neighbor, node, visited)) - return false; - } + visited.add(node); - return true; + for (var neighbor : adjacencyList.get(node)) { + if (neighbor == previous) continue; + + if (!depthFirstSearch(neighbor, node, visited)) return false; } + + return true; + } } diff --git a/java/268-Missing-Number.java b/java/268-Missing-Number.java index 2f0bd92ae..dee14aad4 100644 --- a/java/268-Missing-Number.java +++ b/java/268-Missing-Number.java @@ -1,10 +1,11 @@ class Solution { - public int missingNumber(int[] nums) { - int sum = 0; - int total = nums.length * (nums.length+1)/2; - for(int i = 0; i < nums.length; i++){ - sum += nums[i]; - } - return total - sum; + + public int missingNumber(int[] nums) { + int sum = 0; + int total = nums.length * (nums.length + 1) / 2; + for (int i = 0; i < nums.length; i++) { + sum += nums[i]; } + return total - sum; + } } diff --git a/java/27-Remove-Element.java b/java/27-Remove-Element.java index 1a3853407..4d11b6535 100644 --- a/java/27-Remove-Element.java +++ b/java/27-Remove-Element.java @@ -1,21 +1,22 @@ class Solution { - public void swap(int[] a, int i, int j) { - int temp = a[i]; - a[i] = a[j]; - a[j] = temp; - } - public int removeElement(int[] nums, int val) { - int boundary = nums.length-1; - int i = 0; - while (i <= boundary) { - if (nums[i] == val) { - swap(nums, i, boundary); - boundary -= 1; - } - else { - i += 1; - } - } - return i; + + public void swap(int[] a, int i, int j) { + int temp = a[i]; + a[i] = a[j]; + a[j] = temp; + } + + public int removeElement(int[] nums, int val) { + int boundary = nums.length - 1; + int i = 0; + while (i <= boundary) { + if (nums[i] == val) { + swap(nums, i, boundary); + boundary -= 1; + } else { + i += 1; + } } + return i; + } } diff --git a/java/271-Encode-and-Decode-Strings.java b/java/271-Encode-and-Decode-Strings.java index fc6f693e7..ebfbc23ad 100644 --- a/java/271-Encode-and-Decode-Strings.java +++ b/java/271-Encode-and-Decode-Strings.java @@ -1,28 +1,24 @@ public class Solution { - public String encode(List strs) { - StringBuilder encodedString = new StringBuilder(); - for (String str : strs) { - encodedString.append(str.length()) - .append("#") - .append(str); - } - return encodedString.toString(); + public String encode(List strs) { + StringBuilder encodedString = new StringBuilder(); + for (String str : strs) { + encodedString.append(str.length()).append("#").append(str); } + return encodedString.toString(); + } - public List decode(String str) { + public List decode(String str) { + List list = new ArrayList<>(); + int i = 0; + while (i < str.length()) { + int j = i; + while (str.charAt(j) != '#') j++; - List list = new ArrayList<>(); - int i = 0; - while (i < str.length()) { - int j = i; - while (str.charAt(j) != '#') - j++; - - int length = Integer.valueOf(str.substring(i, j)); - i = j + 1 + length; - list.add(str.substring(j + 1, i)); - } - return list; + int length = Integer.valueOf(str.substring(i, j)); + i = j + 1 + length; + list.add(str.substring(j + 1, i)); } + return list; + } } diff --git a/java/279-Perfect-Squares.java b/java/279-Perfect-Squares.java index 58e4f6bd5..64ce66421 100644 --- a/java/279-Perfect-Squares.java +++ b/java/279-Perfect-Squares.java @@ -1,27 +1,28 @@ -//This is a BFS based approach. +//This is a BFS based approach. //We can also do this problem similar to coin change but the Time and space complexity will remain same (Just an extra queue in this one stil linear space). class Solution { - public int numSquares(int n) { - Queue q = new LinkedList<>(); - //add visited array so we don't go to values which we have traversed already (similar to dp) otherwise this will give tle - HashSet visited = new HashSet<>(); - int ans = 0; - q.offer(n); - while (!q.isEmpty()) { - int size = q.size(); - for (int i = 0; i q = new LinkedList<>(); + //add visited array so we don't go to values which we have traversed already (similar to dp) otherwise this will give tle + HashSet visited = new HashSet<>(); + int ans = 0; + q.offer(n); + while (!q.isEmpty()) { + int size = q.size(); + for (int i = 0; i < size; i++) { + int cur = q.poll(); + if (cur == 0) return ans; + for (int j = 1; j <= cur / j; j++) { + if (!visited.contains(cur - j * j)) { + q.offer(cur - j * j); + visited.add(cur - j * j); + } } - return -1; + } + ans++; } + return -1; + } } diff --git a/java/286-Walls-and-Gates.java b/java/286-Walls-and-Gates.java index 3012f12a2..7a9a7eb46 100644 --- a/java/286-Walls-and-Gates.java +++ b/java/286-Walls-and-Gates.java @@ -2,36 +2,36 @@ //Time complexity will be O(N^2) since we are basically traversing every value in the grid. class Solution { - public void wallsAndGates(int[][] rooms) { - Queue q = new LinkedList<>(); - int m = rooms.length; - int n = rooms[0].length; - for (int i=0; i=m || y>=n || x<0 || y<0 || rooms[x][y]!=Integer.MAX_VALUE) - continue; - q.add(new int[]{x, y}); - //since cur is basically the index of door (which is equal to 0) - //So, we can just grab that value (rooms[row][col]) and add 1 to it and change it every time - rooms[x][y] = rooms[row][col]+1; - //So, one level further from door (value 0) is equal to 1. Now, we do bfs from that position so value will be 2 and so on. - } - } + + public void wallsAndGates(int[][] rooms) { + Queue q = new LinkedList<>(); + int m = rooms.length; + int n = rooms[0].length; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (rooms[i][j] == 0) q.add(new int[] { i, j }); + } + } + if (q.size() == 0) return; + int[][] dirs = { { -1, 0 }, { 0, -1 }, { 1, 0 }, { 0, 1 } }; + int dis = 0; + while (!q.isEmpty()) { + ++dis; + int[] cur = q.poll(); + int row = cur[0]; + int col = cur[1]; + for (int[] dir : dirs) { + int x = row + dir[0]; + int y = col + dir[1]; + if ( + x >= m || y >= n || x < 0 || y < 0 || rooms[x][y] != Integer.MAX_VALUE + ) continue; + q.add(new int[] { x, y }); + //since cur is basically the index of door (which is equal to 0) + //So, we can just grab that value (rooms[row][col]) and add 1 to it and change it every time + rooms[x][y] = rooms[row][col] + 1; + //So, one level further from door (value 0) is equal to 1. Now, we do bfs from that position so value will be 2 and so on. + } } + } } diff --git a/java/287-Find-the-Duplicate-Number.java b/java/287-Find-the-Duplicate-Number.java index 83577fd29..8d6f65467 100644 --- a/java/287-Find-the-Duplicate-Number.java +++ b/java/287-Find-the-Duplicate-Number.java @@ -3,23 +3,24 @@ // Space Complexity: O(1) class Solution { - public int findDuplicate(int[] nums) { - int fast = nums[0]; - int slow = nums[0]; - boolean first = true; - while (first || fast!=slow) { - if (first) first = false; - slow = nums[slow]; - fast = nums[nums[fast]]; - if (fast == slow) break; - } - int slow2 = nums[0]; - while (slow2!=slow) { - if (first) first = false; - slow2 = nums[slow2]; - slow = nums[slow]; - if (slow2 == slow) return slow; - } - return slow; + + public int findDuplicate(int[] nums) { + int fast = nums[0]; + int slow = nums[0]; + boolean first = true; + while (first || fast != slow) { + if (first) first = false; + slow = nums[slow]; + fast = nums[nums[fast]]; + if (fast == slow) break; + } + int slow2 = nums[0]; + while (slow2 != slow) { + if (first) first = false; + slow2 = nums[slow2]; + slow = nums[slow]; + if (slow2 == slow) return slow; } + return slow; + } } diff --git a/java/295-Find-Median-from-Data-Stream.java b/java/295-Find-Median-from-Data-Stream.java index a1c04145f..e08c83e73 100644 --- a/java/295-Find-Median-from-Data-Stream.java +++ b/java/295-Find-Median-from-Data-Stream.java @@ -1,33 +1,37 @@ class MedianFinder { - private Queue smallHeap; //small elements - maxHeap - private Queue largeHeap; //large elements - minHeap - - public MedianFinder() { - smallHeap = new PriorityQueue<>((a, b) -> b - a); - largeHeap = new PriorityQueue<>((a, b) -> a - b); + + private Queue smallHeap; //small elements - maxHeap + private Queue largeHeap; //large elements - minHeap + + public MedianFinder() { + smallHeap = new PriorityQueue<>((a, b) -> b - a); + largeHeap = new PriorityQueue<>((a, b) -> a - b); + } + + public void addNum(int num) { + smallHeap.add(num); + if ( + smallHeap.size() - largeHeap.size() > 1 || + !largeHeap.isEmpty() && + smallHeap.peek() > largeHeap.peek() + ) { + largeHeap.add(smallHeap.poll()); } - - public void addNum(int num) { - smallHeap.add(num); - if (smallHeap.size() - largeHeap.size() > 1 || !largeHeap.isEmpty() && smallHeap.peek() > largeHeap.peek()) { - largeHeap.add(smallHeap.poll()); - } - if (largeHeap.size() - smallHeap.size() > 1) { - smallHeap.add(largeHeap.poll()); - } + if (largeHeap.size() - smallHeap.size() > 1) { + smallHeap.add(largeHeap.poll()); } - - public double findMedian() { - if (smallHeap.size() == largeHeap.size()) { - return (double)(largeHeap.peek() + smallHeap.peek()) / 2; - } else if (smallHeap.size() > largeHeap.size()) { - return (double)smallHeap.peek(); - } else { - return (double)largeHeap.peek(); - } + } + + public double findMedian() { + if (smallHeap.size() == largeHeap.size()) { + return (double) (largeHeap.peek() + smallHeap.peek()) / 2; + } else if (smallHeap.size() > largeHeap.size()) { + return (double) smallHeap.peek(); + } else { + return (double) largeHeap.peek(); } + } } - /** * Your MedianFinder object will be instantiated and called as such: * MedianFinder obj = new MedianFinder(); diff --git a/java/297-Serialize-and-Deserialize-Binary-Tree.java b/java/297-Serialize-and-Deserialize-Binary-Tree.java index 1dedb1e8d..70a3ec865 100644 --- a/java/297-Serialize-and-Deserialize-Binary-Tree.java +++ b/java/297-Serialize-and-Deserialize-Binary-Tree.java @@ -8,47 +8,46 @@ * } */ public class Codec { - - private int i; - // Encodes a tree to a single string. - public String serialize(TreeNode root) { - List list = new ArrayList<>(); - serializeDFS(root, list); - - return String.join(",", list); - } - - private void serializeDFS(TreeNode root, List list) { - if (root == null) { - list.add("N"); - return; - } - list.add(String.valueOf(root.val)); - serializeDFS(root.left, list); - serializeDFS(root.right, list); - } + private int i; + + // Encodes a tree to a single string. + public String serialize(TreeNode root) { + List list = new ArrayList<>(); + serializeDFS(root, list); + + return String.join(",", list); + } - // Decodes your encoded data to tree. - public TreeNode deserialize(String data) { - String[] tokens = data.split(","); - return deserializeDFS(tokens); + private void serializeDFS(TreeNode root, List list) { + if (root == null) { + list.add("N"); + return; } - - private TreeNode deserializeDFS(String[] tokens) { - String token = tokens[this.i]; - if (token.equals("N")) { - this.i++; - return null; - } - var node = new TreeNode(Integer.parseInt(token)); - this.i++; - node.left = deserializeDFS(tokens); - node.right = deserializeDFS(tokens); - return node; + list.add(String.valueOf(root.val)); + serializeDFS(root.left, list); + serializeDFS(root.right, list); + } + + // Decodes your encoded data to tree. + public TreeNode deserialize(String data) { + String[] tokens = data.split(","); + return deserializeDFS(tokens); + } + + private TreeNode deserializeDFS(String[] tokens) { + String token = tokens[this.i]; + if (token.equals("N")) { + this.i++; + return null; } + var node = new TreeNode(Integer.parseInt(token)); + this.i++; + node.left = deserializeDFS(tokens); + node.right = deserializeDFS(tokens); + return node; + } } - // Your Codec object will be instantiated and called as such: // Codec ser = new Codec(); // Codec deser = new Codec(); diff --git a/java/3-Longest-Substring-Without-Repeating-Characters.java b/java/3-Longest-Substring-Without-Repeating-Characters.java index 977e1d103..d460e5710 100644 --- a/java/3-Longest-Substring-Without-Repeating-Characters.java +++ b/java/3-Longest-Substring-Without-Repeating-Characters.java @@ -1,16 +1,17 @@ class Solution { - public int lengthOfLongestSubstring(String s) { - HashSet set = new HashSet<>(); - int left = 0; - int ans = 0; - for (int right = 0; right set = new HashSet<>(); + int left = 0; + int ans = 0; + for (int right = 0; right < s.length(); right++) { + while (set.contains(s.charAt(right))) { + set.remove(s.charAt(left)); + left++; + } + set.add(s.charAt(right)); + ans = Math.max(ans, right - left + 1); } + return ans; + } } diff --git a/java/300-Longest-Increasing-Subsequence.java b/java/300-Longest-Increasing-Subsequence.java index 85c8169f9..081a03c0c 100644 --- a/java/300-Longest-Increasing-Subsequence.java +++ b/java/300-Longest-Increasing-Subsequence.java @@ -1,20 +1,21 @@ class Solution { - public int lengthOfLIS(int[] nums) { - //O(n^2) - if(nums.length == 1) return 1; - - int[] LIS = new int[nums.length]; - Arrays.fill(LIS,1); - int maximumSoFar = 1; - - for (int i = nums.length - 1 ; i >= 0; i--) { - for(int j= i + 1 ; j < nums.length ; j++){ - if (nums[i] < nums[j]) { - LIS[i] = Math.max(1 + LIS[j], LIS[i]); - } - } - maximumSoFar = Math.max(maximumSoFar, LIS[i]); + + public int lengthOfLIS(int[] nums) { + //O(n^2) + if (nums.length == 1) return 1; + + int[] LIS = new int[nums.length]; + Arrays.fill(LIS, 1); + int maximumSoFar = 1; + + for (int i = nums.length - 1; i >= 0; i--) { + for (int j = i + 1; j < nums.length; j++) { + if (nums[i] < nums[j]) { + LIS[i] = Math.max(1 + LIS[j], LIS[i]); } - return maximumSoFar; + } + maximumSoFar = Math.max(maximumSoFar, LIS[i]); } -} \ No newline at end of file + return maximumSoFar; + } +} diff --git a/java/309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.java b/java/309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.java index 1cacc99df..0c42e65c5 100644 --- a/java/309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.java +++ b/java/309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.java @@ -1,29 +1,35 @@ class Solution { - public int maxProfit(int[] prices) { - Map cache = new HashMap<>(); - return dfs(prices, cache, 0, true); - } - public int dfs(int[] prices, Map cache, int index, boolean buying) { - if (index >= prices.length) { - return 0; - } - String key = index+"-"+buying; + public int maxProfit(int[] prices) { + Map cache = new HashMap<>(); + return dfs(prices, cache, 0, true); + } - if (cache.containsKey(key)) { - return cache.get(key); - } + public int dfs( + int[] prices, + Map cache, + int index, + boolean buying + ) { + if (index >= prices.length) { + return 0; + } + String key = index + "-" + buying; - int cooldown = dfs(prices, cache, index + 1, buying); - int buyOsell = Integer.MIN_VALUE; + if (cache.containsKey(key)) { + return cache.get(key); + } - if (buying) { - buyOsell = dfs(prices, cache, index + 1, !buying) - prices[index]; - } else { - buyOsell = dfs(prices, cache, index + 2, !buying) + prices[index]; - } - - cache.put(key, Math.max(buyOsell, cooldown)); - return cache.get(key); + int cooldown = dfs(prices, cache, index + 1, buying); + int buyOsell = Integer.MIN_VALUE; + + if (buying) { + buyOsell = dfs(prices, cache, index + 1, !buying) - prices[index]; + } else { + buyOsell = dfs(prices, cache, index + 2, !buying) + prices[index]; } -} \ No newline at end of file + + cache.put(key, Math.max(buyOsell, cooldown)); + return cache.get(key); + } +} diff --git a/java/322-Coin-Change.java b/java/322-Coin-Change.java index e8e35336d..a5d4e9f18 100644 --- a/java/322-Coin-Change.java +++ b/java/322-Coin-Change.java @@ -1,22 +1,23 @@ import java.util.Arrays; class Solution { - public int coinChange(int[] coins, int amount) { - if (amount < 0 || coins.length == 0 || coins == null) { - return 0; - } - int[] dp = new int[amount + 1]; - Arrays.fill(dp, amount + 1); - dp[0] = 0; - for(int i = 1; i <= amount; i++){ - for(int coin : coins){ - if(i - coin >= 0){ - dp[i] = Math.min(dp[i], 1 + dp[i - coin]); - } - } - } + public int coinChange(int[] coins, int amount) { + if (amount < 0 || coins.length == 0 || coins == null) { + return 0; + } + int[] dp = new int[amount + 1]; + Arrays.fill(dp, amount + 1); + dp[0] = 0; - return dp[amount] != amount + 1? dp[amount]: -1; + for (int i = 1; i <= amount; i++) { + for (int coin : coins) { + if (i - coin >= 0) { + dp[i] = Math.min(dp[i], 1 + dp[i - coin]); + } + } } -} \ No newline at end of file + + return dp[amount] != amount + 1 ? dp[amount] : -1; + } +} diff --git a/java/323-Number-of-Connected-Components-in-an-Undirected-Graph.java b/java/323-Number-of-Connected-Components-in-an-Undirected-Graph.java index 2b95f88d5..17c8b24fe 100644 --- a/java/323-Number-of-Connected-Components-in-an-Undirected-Graph.java +++ b/java/323-Number-of-Connected-Components-in-an-Undirected-Graph.java @@ -1,53 +1,54 @@ class Solution { - private int[] parent; - private int[] rank; - - public int countComponents(int n, int[][] edges) { - parent = new int[n]; - rank = new int[n]; - - for (int i = 0; i < n; i++) { - parent[i] = i; - rank[i] = 1; - } - - int result = n; - for (int i = 0; i < edges.length; i++) { - if (union(edges[i][0], edges[i][1]) == 1) { - result--; - } - } - - return result; + + private int[] parent; + private int[] rank; + + public int countComponents(int n, int[][] edges) { + parent = new int[n]; + rank = new int[n]; + + for (int i = 0; i < n; i++) { + parent[i] = i; + rank[i] = 1; } - private int find(int node) { - int result = node; + int result = n; + for (int i = 0; i < edges.length; i++) { + if (union(edges[i][0], edges[i][1]) == 1) { + result--; + } + } + + return result; + } - while (parent[result] != result) { - parent[result] = parent[parent[result]]; - result = parent[result]; - } + private int find(int node) { + int result = node; - return result; + while (parent[result] != result) { + parent[result] = parent[parent[result]]; + result = parent[result]; } - - private int union(int n1, int n2) { - int p1 = this.find(n1); - int p2 = this.find(n2); - - if (p1 == p2) { - return 0; - } - - if (rank[p2] > rank[p1]) { - parent[p1] = p2; - rank[p2] += rank[p1]; - } else { - parent[p2] = p1; - rank[p1] += rank[p2]; - } - - return 1; + + return result; + } + + private int union(int n1, int n2) { + int p1 = this.find(n1); + int p2 = this.find(n2); + + if (p1 == p2) { + return 0; } + + if (rank[p2] > rank[p1]) { + parent[p1] = p2; + rank[p2] += rank[p1]; + } else { + parent[p2] = p1; + rank[p1] += rank[p2]; + } + + return 1; + } } diff --git a/java/329-Longest-Increasing-Path-in-a-Matrix.java b/java/329-Longest-Increasing-Path-in-a-Matrix.java index 80b8c6de6..4eeac8bcc 100644 --- a/java/329-Longest-Increasing-Path-in-a-Matrix.java +++ b/java/329-Longest-Increasing-Path-in-a-Matrix.java @@ -1,37 +1,41 @@ //Another similar problem: https://leetcode.com/contest/weekly-contest-300/problems/number-of-increasing-paths-in-a-grid/ class Solution { - public int longestIncreasingPath(int[][] matrix) { - int m = matrix.length; - int n = matrix[0].length; - int[][] dp = new int[m][n]; - for (int d[]: dp) - Arrays.fill(d, -1); - for (int i = 0; i=m || j>=n || i<0 || j<0 || matrix[i][j]<=parent) - return 0; - parent = matrix[i][j]; - if (dp[i][j]!=-1) - return dp[i][j]; - int left = dfs(matrix, dp, m, n, i, j-1, parent); - int right = dfs(matrix, dp, m, n, i, j+1, parent); - int bottom = dfs(matrix, dp, m, n, i+1, j, parent); - int top = dfs(matrix, dp, m, n, i-1, j, parent); - dp[i][j] = 1+Math.max(Math.max(left, right), Math.max(top, bottom)); - return dp[i][j]; + int max = Integer.MIN_VALUE; + for (int[] d : dp) { + for (int i : d) max = Math.max(i, max); } + return max; + } + + public int dfs( + int[][] matrix, + int[][] dp, + int m, + int n, + int i, + int j, + int parent + ) { + if (i >= m || j >= n || i < 0 || j < 0 || matrix[i][j] <= parent) return 0; + parent = matrix[i][j]; + if (dp[i][j] != -1) return dp[i][j]; + int left = dfs(matrix, dp, m, n, i, j - 1, parent); + int right = dfs(matrix, dp, m, n, i, j + 1, parent); + int bottom = dfs(matrix, dp, m, n, i + 1, j, parent); + int top = dfs(matrix, dp, m, n, i - 1, j, parent); + dp[i][j] = 1 + Math.max(Math.max(left, right), Math.max(top, bottom)); + return dp[i][j]; + } } diff --git a/java/33-Search-In-Rotated-Sorted-Array.java b/java/33-Search-In-Rotated-Sorted-Array.java index 424259ac2..1b695a98c 100644 --- a/java/33-Search-In-Rotated-Sorted-Array.java +++ b/java/33-Search-In-Rotated-Sorted-Array.java @@ -1,46 +1,47 @@ class Solution { - public int search(int[] nums, int target) { - int minIndex = minIndex(nums); - int leftSearch = binarySearch(nums, 0, minIndex - 1, target); - int rightSearch = binarySearch(nums, minIndex, nums.length - 1, target); - if(leftSearch != -1){ - return leftSearch; - } else if(rightSearch != -1){ - return rightSearch; - } else { - return -1; - } + + public int search(int[] nums, int target) { + int minIndex = minIndex(nums); + int leftSearch = binarySearch(nums, 0, minIndex - 1, target); + int rightSearch = binarySearch(nums, minIndex, nums.length - 1, target); + if (leftSearch != -1) { + return leftSearch; + } else if (rightSearch != -1) { + return rightSearch; + } else { + return -1; } - - public int minIndex(int[] nums){ - int start = 0; - int end = nums.length - 1; - while(start <= end){ - int mid = start + (end - start)/2; - int prev = (mid - 1 + nums.length)%nums.length; - int next = (mid + 1)%nums.length; - if(nums[mid] <= nums[prev] && nums[mid] <= nums[next]){ - return mid; - } else if(nums[mid] <= nums[end]){ - end = mid - 1; - } else if(nums[mid] >= nums[start]){ - start = mid + 1; - } - } - return -1; + } + + public int minIndex(int[] nums) { + int start = 0; + int end = nums.length - 1; + while (start <= end) { + int mid = start + (end - start) / 2; + int prev = (mid - 1 + nums.length) % nums.length; + int next = (mid + 1) % nums.length; + if (nums[mid] <= nums[prev] && nums[mid] <= nums[next]) { + return mid; + } else if (nums[mid] <= nums[end]) { + end = mid - 1; + } else if (nums[mid] >= nums[start]) { + start = mid + 1; + } } - - public int binarySearch(int[] nums, int start, int end, int target){ - while(start <= end){ - int mid = start + (end-start)/2; - if(nums[mid] == target){ - return mid; - } else if(nums[mid] < target){ - start = mid + 1; - } else { - end = mid - 1; - } - } - return -1; + return -1; + } + + public int binarySearch(int[] nums, int start, int end, int target) { + while (start <= end) { + int mid = start + (end - start) / 2; + if (nums[mid] == target) { + return mid; + } else if (nums[mid] < target) { + start = mid + 1; + } else { + end = mid - 1; + } } -} \ No newline at end of file + return -1; + } +} diff --git a/java/338-Counting-Bits.java b/java/338-Counting-Bits.java index 6f265d8cf..e90045ab2 100644 --- a/java/338-Counting-Bits.java +++ b/java/338-Counting-Bits.java @@ -1,20 +1,20 @@ class Solution { - public int[] countBits(int n) { - - int[] ans = new int[n+1]; - - for(int i = 0; i <= n; i++){ - ans[i] = count(i); - } - return ans; + + public int[] countBits(int n) { + int[] ans = new int[n + 1]; + + for (int i = 0; i <= n; i++) { + ans[i] = count(i); } - - private int count(int x){ - int count = 0; - while(x != 0){ - x &= x - 1; - count++; - } - return count; + return ans; + } + + private int count(int x) { + int count = 0; + while (x != 0) { + x &= x - 1; + count++; } + return count; + } } diff --git a/java/347-Top-K-Frequent-Elements.java b/java/347-Top-K-Frequent-Elements.java index 5f801885d..dfe71a113 100644 --- a/java/347-Top-K-Frequent-Elements.java +++ b/java/347-Top-K-Frequent-Elements.java @@ -1,77 +1,88 @@ class Solution1 { - /** - * Time Complexity: O(nlog(k)) - * Space Complexity: O(n) - */ - public int[] topKFrequent(int[] nums, int k) { - int[] arr = new int[k]; - HashMap map = new HashMap<>(); - for (int num: nums) - map.put(num, map.getOrDefault(num, 0)+1); - PriorityQueue> pq = new PriorityQueue<>((a, b)->a.getValue()-b.getValue()); - for (Map.Entry it: map.entrySet()) { - pq.add(it); - if (pq.size()>k) - pq.poll(); - } - int i = k; - while (!pq.isEmpty()) { - arr[--i] = pq.poll().getKey(); - } - return arr; + + /** + * Time Complexity: O(nlog(k)) + * Space Complexity: O(n) + */ + public int[] topKFrequent(int[] nums, int k) { + int[] arr = new int[k]; + HashMap map = new HashMap<>(); + for (int num : nums) map.put(num, map.getOrDefault(num, 0) + 1); + PriorityQueue> pq = new PriorityQueue<>( + (a, b) -> + a.getValue() - b.getValue() + ); + for (Map.Entry it : map.entrySet()) { + pq.add(it); + if (pq.size() > k) pq.poll(); + } + int i = k; + while (!pq.isEmpty()) { + arr[--i] = pq.poll().getKey(); } + return arr; + } } class Solution2 { - /** - * Time Complexity: O(n) - * Space Complexity: O(n) - */ - public int[] topKFrequent(int[] numbers, int k) { - HashMap map = new HashMap<>(); - for (int number : numbers) - map.put(number, map.getOrDefault(number, 0) + 1); - int size = map.size(); - int[] keys = new int[size]; - int i = 0; - for (int key : map.keySet()) - keys[i++] = key; + /** + * Time Complexity: O(n) + * Space Complexity: O(n) + */ + public int[] topKFrequent(int[] numbers, int k) { + HashMap map = new HashMap<>(); + for (int number : numbers) map.put(number, map.getOrDefault(number, 0) + 1); - select(keys, map, 0, size - 1, size - k); - return Arrays.copyOfRange(keys, size - k, size); - } + int size = map.size(); + int[] keys = new int[size]; + int i = 0; + for (int key : map.keySet()) keys[i++] = key; - // Modified implementation of Hoare's selection algorithm: - - private void select(int[] keys, Map map, int left, int right, int kSmallest) { - while (left != right) { - int pivot = partition(keys, map, left, right, (left + right) / 2); + select(keys, map, 0, size - 1, size - k); + return Arrays.copyOfRange(keys, size - k, size); + } - if (kSmallest == pivot) return; + // Modified implementation of Hoare's selection algorithm: - if (kSmallest < pivot) right = pivot - 1; - else left = pivot + 1; - } - } + private void select( + int[] keys, + Map map, + int left, + int right, + int kSmallest + ) { + while (left != right) { + int pivot = partition(keys, map, left, right, (left + right) / 2); - private int partition(int[] keys, Map map,int left, int right, int pivot) { - int pivotValue = map.get(keys[pivot]); - swap(keys, pivot, right); - int index = left; + if (kSmallest == pivot) return; + + if (kSmallest < pivot) right = pivot - 1; else left = pivot + 1; + } + } + + private int partition( + int[] keys, + Map map, + int left, + int right, + int pivot + ) { + int pivotValue = map.get(keys[pivot]); + swap(keys, pivot, right); + int index = left; + + for (int i = left; i <= right; i++) if (map.get(keys[i]) < pivotValue) { + swap(keys, i, index); + index++; + } + swap(keys, right, index); + return index; + } - for (int i = left; i <= right; i++) - if (map.get(keys[i]) < pivotValue) { - swap(keys, i, index); - index++; - } - swap(keys, right, index); - return index; - } - - private void swap(int[] array, int i1, int i2) { - int temp = array[i1]; - array[i1] = array[i2]; - array[i2] = temp; - } + private void swap(int[] array, int i1, int i2) { + int temp = array[i1]; + array[i1] = array[i2]; + array[i2] = temp; + } } diff --git a/java/36-valid-sudoku.java b/java/36-valid-sudoku.java index 89569079c..85c404d61 100644 --- a/java/36-valid-sudoku.java +++ b/java/36-valid-sudoku.java @@ -1,29 +1,30 @@ -class Solution { - public boolean isValidSudoku(char[][] board) { - HashSet h1 = new HashSet(); - - for(int i=0; i < 9; i++){ - for(int j=0; j< 9; j++){ - if(board[i][j] != '.'){ - - //Check whether HashSet contains duplicate elements in row and column - if(h1.contains("row" + i + board[i][j]) || h1.contains("col" + j + board[i][j]) ){ - return false; - } - h1.add("row" + i + board[i][j]); - h1.add("col" + j + board[i][j]); - - - //Check whether Box contains duplicate elements in it - if(h1.contains("box"+ (i/3) + (j/3) + board[i][j])){ - return false; - } - h1.add("box"+ (i/3) + (j/3) + board[i][j]); - } - } - } - - - return true; - } -} +class Solution { + + public boolean isValidSudoku(char[][] board) { + HashSet h1 = new HashSet(); + + for (int i = 0; i < 9; i++) { + for (int j = 0; j < 9; j++) { + if (board[i][j] != '.') { + //Check whether HashSet contains duplicate elements in row and column + if ( + h1.contains("row" + i + board[i][j]) || + h1.contains("col" + j + board[i][j]) + ) { + return false; + } + h1.add("row" + i + board[i][j]); + h1.add("col" + j + board[i][j]); + + //Check whether Box contains duplicate elements in it + if (h1.contains("box" + (i / 3) + (j / 3) + board[i][j])) { + return false; + } + h1.add("box" + (i / 3) + (j / 3) + board[i][j]); + } + } + } + + return true; + } +} diff --git a/java/37-Sudoku-Solver.java b/java/37-Sudoku-Solver.java index 076aa712a..09dda503d 100644 --- a/java/37-Sudoku-Solver.java +++ b/java/37-Sudoku-Solver.java @@ -2,54 +2,54 @@ //mix of search a 2d matrix and valid sudoku class Solution { - public void solveSudoku(char[][] board) { - solve(board); - } - - public boolean solve(char[][] board) { - //traverse the complete sudoku and look for empty value - for (int i = 0; i<9; i++) { - for (int j=0; j<9; j++) { - //look for '.' (empty block) - if (board[i][j] == '.') { - //try filling all values - for (char c='1'; c<='9'; c++) { - //check if we can put that value at that place - //we will have a function for this which will check all the - //three conditions for a valid sudoku - if (isValid(board, i, j, c)) { - board[i][j] = c; - //check whether the new board is solvable and just return true if it is - //so, we can just have only one sudoku combination. - //else backtrack, i.e., make it '.' again. - if (solve(board)) - return true; - else - board[i][j] = '.'; - } - } - //if the board[i][j] is empty and we checked all values and - //nothing from '0' to '9' can be added then return false - //as this is unsolvable - return false; - } + + public void solveSudoku(char[][] board) { + solve(board); + } + + public boolean solve(char[][] board) { + //traverse the complete sudoku and look for empty value + for (int i = 0; i < 9; i++) { + for (int j = 0; j < 9; j++) { + //look for '.' (empty block) + if (board[i][j] == '.') { + //try filling all values + for (char c = '1'; c <= '9'; c++) { + //check if we can put that value at that place + //we will have a function for this which will check all the + //three conditions for a valid sudoku + if (isValid(board, i, j, c)) { + board[i][j] = c; + //check whether the new board is solvable and just return true if it is + //so, we can just have only one sudoku combination. + //else backtrack, i.e., make it '.' again. + if (solve(board)) return true; else board[i][j] = '.'; } + } + //if the board[i][j] is empty and we checked all values and + //nothing from '0' to '9' can be added then return false + //as this is unsolvable + return false; } - return true; + } } - - public boolean isValid (char[][] board, int row, int col, char c) { - for (int i = 0; i<9; i++) { - //row check - if (board[row][i]==c) return false; - //col check - if (board[i][col]==c) return false; - //boxes check - //for this draw a sudoku and see by marking boxes and choosing a random postion - //this is hard to explain but try this one - //you'll get to the formula by yourself - if (board[3*(row/3)+i/3][3*(col/3)+i%3]==c) return false; - } - return true; + return true; + } + + public boolean isValid(char[][] board, int row, int col, char c) { + for (int i = 0; i < 9; i++) { + //row check + if (board[row][i] == c) return false; + //col check + if (board[i][col] == c) return false; + //boxes check + //for this draw a sudoku and see by marking boxes and choosing a random postion + //this is hard to explain but try this one + //you'll get to the formula by yourself + if ( + board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c + ) return false; } + return true; + } } diff --git a/java/371-Sum-of-Two-Integers.java b/java/371-Sum-of-Two-Integers.java index ff641469f..bac4c5b7d 100644 --- a/java/371-Sum-of-Two-Integers.java +++ b/java/371-Sum-of-Two-Integers.java @@ -1,10 +1,11 @@ class Solution { - public int getSum(int a, int b) { - while (b != 0) { - int tmp = (a & b) << 1; - a = (a ^ b); - b = tmp; - } - return a; + + public int getSum(int a, int b) { + while (b != 0) { + int tmp = (a & b) << 1; + a = (a ^ b); + b = tmp; } + return a; + } } diff --git a/java/39-Combination-Sum.java b/java/39-Combination-Sum.java index e3b0f4730..52cdf0495 100644 --- a/java/39-Combination-Sum.java +++ b/java/39-Combination-Sum.java @@ -1,24 +1,29 @@ class Solution { - public List> combinationSum(int[] candidates, int target) { - List> ans = new ArrayList>(); - List cur = new ArrayList(); - backtrack(candidates, target, ans, cur, 0); - return ans; - + + public List> combinationSum(int[] candidates, int target) { + List> ans = new ArrayList>(); + List cur = new ArrayList(); + backtrack(candidates, target, ans, cur, 0); + return ans; + } + + public void backtrack( + int[] candidates, + int target, + List> ans, + List cur, + int index + ) { + if (target == 0) { + ans.add(new ArrayList(cur)); + } else if (target < 0 || index >= candidates.length) { + return; + } else { + cur.add(candidates[index]); + backtrack(candidates, target - candidates[index], ans, cur, index); + + cur.remove(cur.get(cur.size() - 1)); + backtrack(candidates, target, ans, cur, index + 1); } - - public void backtrack(int[] candidates, int target, List> ans, List cur, int index) { - if (target == 0) { - ans.add(new ArrayList(cur)); - } else if (target < 0 || index >= candidates.length) { - return; - } else { - cur.add(candidates[index]); - backtrack(candidates, target - candidates[index], ans, cur, index); - - cur.remove(cur.get(cur.size() - 1)); - backtrack(candidates, target, ans, cur, index + 1); - } - - } -} \ No newline at end of file + } +} diff --git a/java/4-Median-of-Two-Sorted-Arrays.java b/java/4-Median-of-Two-Sorted-Arrays.java index 8a3854f1a..d7cfeed9d 100644 --- a/java/4-Median-of-Two-Sorted-Arrays.java +++ b/java/4-Median-of-Two-Sorted-Arrays.java @@ -28,51 +28,52 @@ public double findMedianSortedArrays(int[] nums1, int[] nums2) { // Extra Space: O(1) class Solution { - public double findMedianSortedArrays(int[] nums1, int[] nums2) { - int m = nums1.length; - int n = nums2.length; - - if(m > n){ - return findMedianSortedArrays(nums2, nums1); - } - - int total = m + n; - int half = (total + 1) / 2; - - int left = 0; - int right = m; - - var result = 0.0; - - while(left <= right){ - int i = left + (right - left) / 2; - int j = half - i; - - // get the four points around possible median - int left1 = (i > 0) ? nums1[i - 1] : Integer.MIN_VALUE; - int right1 = (i < m) ? nums1[i] : Integer.MAX_VALUE; - int left2 = (j > 0) ? nums2[j - 1] : Integer.MIN_VALUE; - int right2 = (j < n) ? nums2[j] : Integer.MAX_VALUE; - - // partition is correct - if (left1 <= right2 && left2 <= right1) { - // even - if (total % 2 == 0) { - result = (Math.max(left1, left2) + Math.min(right1, right2)) / 2.0; - // odd - } else { - result = Math.max(left1, left2); - } - break; - } - // partition is wrong (update left/right pointers) - else if (left1 > right2) { - right = i - 1; - } else { - left = i + 1; - } + + public double findMedianSortedArrays(int[] nums1, int[] nums2) { + int m = nums1.length; + int n = nums2.length; + + if (m > n) { + return findMedianSortedArrays(nums2, nums1); + } + + int total = m + n; + int half = (total + 1) / 2; + + int left = 0; + int right = m; + + var result = 0.0; + + while (left <= right) { + int i = left + (right - left) / 2; + int j = half - i; + + // get the four points around possible median + int left1 = (i > 0) ? nums1[i - 1] : Integer.MIN_VALUE; + int right1 = (i < m) ? nums1[i] : Integer.MAX_VALUE; + int left2 = (j > 0) ? nums2[j - 1] : Integer.MIN_VALUE; + int right2 = (j < n) ? nums2[j] : Integer.MAX_VALUE; + + // partition is correct + if (left1 <= right2 && left2 <= right1) { + // even + if (total % 2 == 0) { + result = (Math.max(left1, left2) + Math.min(right1, right2)) / 2.0; + // odd + } else { + result = Math.max(left1, left2); } - - return result; + break; + } + // partition is wrong (update left/right pointers) + else if (left1 > right2) { + right = i - 1; + } else { + left = i + 1; + } } + + return result; + } } diff --git a/java/40-Combination-Sum-II.java b/java/40-Combination-Sum-II.java index 819f0ebc8..4c3b4bbf9 100644 --- a/java/40-Combination-Sum-II.java +++ b/java/40-Combination-Sum-II.java @@ -1,25 +1,29 @@ class Solution { - public List> combinationSum2(int[] candidates, int target) { - Arrays.sort(candidates); - List> ans = new ArrayList>(); - List ls = new ArrayList(); - comb(candidates, target, ans, ls, 0); - return ans; - } - - public void comb(int[] candidates, int target, List> ans, List ls, int index) { - if (target == 0) { - ans.add(new ArrayList(ls)); - } - else if (target<0) - return; - else { - for (int i = index; iindex && candidates[i] == candidates[i-1]) continue; - ls.add(candidates[i]); - comb(candidates, target-candidates[i], ans, ls, i+1); - ls.remove(ls.get(ls.size()-1)); - } - } + + public List> combinationSum2(int[] candidates, int target) { + Arrays.sort(candidates); + List> ans = new ArrayList>(); + List ls = new ArrayList(); + comb(candidates, target, ans, ls, 0); + return ans; + } + + public void comb( + int[] candidates, + int target, + List> ans, + List ls, + int index + ) { + if (target == 0) { + ans.add(new ArrayList(ls)); + } else if (target < 0) return; else { + for (int i = index; i < candidates.length; i++) { + if (i > index && candidates[i] == candidates[i - 1]) continue; + ls.add(candidates[i]); + comb(candidates, target - candidates[i], ans, ls, i + 1); + ls.remove(ls.get(ls.size() - 1)); + } } + } } diff --git a/java/416-Partition-Equal-Subset-Sum.java b/java/416-Partition-Equal-Subset-Sum.java index 79072112a..8aab8deeb 100644 --- a/java/416-Partition-Equal-Subset-Sum.java +++ b/java/416-Partition-Equal-Subset-Sum.java @@ -1,27 +1,25 @@ class Solution { - public boolean canPartition(int[] nums) { - int sum = 0; - for (int num: nums) { - sum+=num; - } - if (sum%2!=0) return false; - int target = sum/2; - boolean[][] dp = new boolean[nums.length+1][target+1]; - int n = nums.length; - for (int i = 0; i<=n; i++) { - for (int j = 0; j<=target; j++) { - if (i == 0 || j == 0) { - if (i==0) dp[i][j] = false; - else if (j==0) dp[i][j] = true; - } - else if (j>=nums[i-1]) { - dp[i][j] = dp[i-1][j] || dp[i-1][j-nums[i-1]]; - } - else { - dp[i][j] = dp[i-1][j]; - } - } + + public boolean canPartition(int[] nums) { + int sum = 0; + for (int num : nums) { + sum += num; + } + if (sum % 2 != 0) return false; + int target = sum / 2; + boolean[][] dp = new boolean[nums.length + 1][target + 1]; + int n = nums.length; + for (int i = 0; i <= n; i++) { + for (int j = 0; j <= target; j++) { + if (i == 0 || j == 0) { + if (i == 0) dp[i][j] = false; else if (j == 0) dp[i][j] = true; + } else if (j >= nums[i - 1]) { + dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i - 1]]; + } else { + dp[i][j] = dp[i - 1][j]; } - return dp[n][target]; - } + } + } + return dp[n][target]; + } } diff --git a/java/417-Pacific-Atlantic-Water-Flow.java b/java/417-Pacific-Atlantic-Water-Flow.java index 66404e213..cde0f79fe 100644 --- a/java/417-Pacific-Atlantic-Water-Flow.java +++ b/java/417-Pacific-Atlantic-Water-Flow.java @@ -1,39 +1,41 @@ class Solution { - int[][] dir = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; - public List> pacificAtlantic(int[][] heights) { - List> res = new ArrayList<>(); - - int rows = heights.length, cols = heights[0].length; - boolean[][] pacific = new boolean[rows][cols]; - boolean[][] atlantic = new boolean[rows][cols]; - - for (int i = 0; i < cols; i++) { - dfs(heights, 0, i, Integer.MIN_VALUE, pacific); - dfs(heights, rows - 1, i, Integer.MIN_VALUE, atlantic); - } - - for (int i = 0; i < rows; i++) { - dfs(heights, i, 0, Integer.MIN_VALUE, pacific); - dfs(heights, i, cols - 1, Integer.MIN_VALUE, atlantic); - } - - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { - if (pacific[i][j] && atlantic[i][j]) { - res.add(Arrays.asList(i, j)); - } - } - } - return res; + + int[][] dir = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } }; + + public List> pacificAtlantic(int[][] heights) { + List> res = new ArrayList<>(); + + int rows = heights.length, cols = heights[0].length; + boolean[][] pacific = new boolean[rows][cols]; + boolean[][] atlantic = new boolean[rows][cols]; + + for (int i = 0; i < cols; i++) { + dfs(heights, 0, i, Integer.MIN_VALUE, pacific); + dfs(heights, rows - 1, i, Integer.MIN_VALUE, atlantic); } - - private void dfs(int[][] heights, int i, int j, int prev, boolean[][] ocean) { - if (i < 0 || i >= ocean.length || j < 0 || j >= ocean[0].length) return; - if (heights[i][j] < prev || ocean[i][j]) return; - - ocean[i][j] = true; - for (int[] d: dir) { - dfs(heights, i + d[0], j + d[1], heights[i][j], ocean); + + for (int i = 0; i < rows; i++) { + dfs(heights, i, 0, Integer.MIN_VALUE, pacific); + dfs(heights, i, cols - 1, Integer.MIN_VALUE, atlantic); + } + + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + if (pacific[i][j] && atlantic[i][j]) { + res.add(Arrays.asList(i, j)); } + } + } + return res; + } + + private void dfs(int[][] heights, int i, int j, int prev, boolean[][] ocean) { + if (i < 0 || i >= ocean.length || j < 0 || j >= ocean[0].length) return; + if (heights[i][j] < prev || ocean[i][j]) return; + + ocean[i][j] = true; + for (int[] d : dir) { + dfs(heights, i + d[0], j + d[1], heights[i][j], ocean); } + } } diff --git a/java/42-Trapping-Rain-Water.java b/java/42-Trapping-Rain-Water.java index b1a32ddab..d010a34a5 100644 --- a/java/42-Trapping-Rain-Water.java +++ b/java/42-Trapping-Rain-Water.java @@ -1,22 +1,23 @@ class Solution { - public int trap(int[] heights) { - int left[]=new int[heights.length],right[]=new int[heights.length],max=heights[0],c=0; - - for(int i=0;i=0;i--){ - right[i]=Math.max(heights[i],max); - max=right[i]; - } - System.out.println(Arrays.toString(right)); - for(int i=0;i= 0; i--) { + right[i] = Math.max(heights[i], max); + max = right[i]; + } + System.out.println(Arrays.toString(right)); + for (int i = 0; i < heights.length; i++) { + c = c + Math.min(left[i], right[i]) - heights[i]; + } + return c; + } } diff --git a/java/424-Longest-Repeating-Character-Replacement.java b/java/424-Longest-Repeating-Character-Replacement.java index d8b2bab9e..667f4f21e 100644 --- a/java/424-Longest-Repeating-Character-Replacement.java +++ b/java/424-Longest-Repeating-Character-Replacement.java @@ -1,18 +1,19 @@ class Solution { - public int characterReplacement(String s, int k) { - int[] arr = new int[26]; - int ans = 0; - int max = 0; - int i = 0; - for (int j = 0; jk) { - arr[s.charAt(i)-'A']--; - i++; - } - ans = Math.max(ans, j-i+1); - } - return ans; + + public int characterReplacement(String s, int k) { + int[] arr = new int[26]; + int ans = 0; + int max = 0; + int i = 0; + for (int j = 0; j < s.length(); j++) { + arr[s.charAt(j) - 'A']++; + max = Math.max(max, arr[s.charAt(j) - 'A']); + if (j - i + 1 - max > k) { + arr[s.charAt(i) - 'A']--; + i++; + } + ans = Math.max(ans, j - i + 1); } + return ans; + } } diff --git a/java/435-Non-Overlapping-Intervals.java b/java/435-Non-Overlapping-Intervals.java index 73b3ce24b..dc329e05f 100644 --- a/java/435-Non-Overlapping-Intervals.java +++ b/java/435-Non-Overlapping-Intervals.java @@ -1,28 +1,32 @@ public class Solution { - public int eraseOverlapIntervals(int[][] intervals) { - int intervalsRemoved = 0; - Arrays.sort(intervals, (arr1,arr2) -> Integer.compare(arr1[0], arr2[0])); + public int eraseOverlapIntervals(int[][] intervals) { + int intervalsRemoved = 0; - int[] intervalFirst = intervals[0]; + Arrays.sort(intervals, (arr1, arr2) -> Integer.compare(arr1[0], arr2[0])); - for(int i = 1; i < intervals.length; i++){ - if(firstIntervalwithinSecond(intervalFirst, intervals[i])){ - //mark first interval to be removed - intervalsRemoved++; - // determine which interval to remove - //remove the interval that ends last - if(intervalFirst[1] > intervals[i][1]){ - intervalFirst = intervals[i]; - } - } else { - intervalFirst = intervals[i]; - } - } - return intervalsRemoved; - } + int[] intervalFirst = intervals[0]; - public boolean firstIntervalwithinSecond(int[] intervalFirst, int[] intervalSecond){ - return intervalSecond[0] < intervalFirst[1]; - } + for (int i = 1; i < intervals.length; i++) { + if (firstIntervalwithinSecond(intervalFirst, intervals[i])) { + //mark first interval to be removed + intervalsRemoved++; + // determine which interval to remove + //remove the interval that ends last + if (intervalFirst[1] > intervals[i][1]) { + intervalFirst = intervals[i]; + } + } else { + intervalFirst = intervals[i]; + } + } + return intervalsRemoved; + } + + public boolean firstIntervalwithinSecond( + int[] intervalFirst, + int[] intervalSecond + ) { + return intervalSecond[0] < intervalFirst[1]; + } } diff --git a/java/448-Find-All-Numbers-Disappeared-in-an-Array.java b/java/448-Find-All-Numbers-Disappeared-in-an-Array.java index 0a00858d4..898641f68 100644 --- a/java/448-Find-All-Numbers-Disappeared-in-an-Array.java +++ b/java/448-Find-All-Numbers-Disappeared-in-an-Array.java @@ -1,20 +1,20 @@ // Since the array has values form 0 to n we can use in-place sorting that's O(N) time and constant space. class Solution { - public List findDisappearedNumbers(int[] nums) { - List list = new ArrayList<>(); - for (int i = 0; i findDisappearedNumbers(int[] nums) { + List list = new ArrayList<>(); + for (int i = 0; i < nums.length; i++) { + int correct = nums[i] - 1; + if (nums[i] != nums[correct] && nums[correct] != nums[i]) { + int temp = nums[i]; + nums[i] = nums[correct]; + nums[correct] = temp; + i--; + } } + for (int i = 0; i < nums.length; i++) { + if (nums[i] - 1 != i) list.add(i + 1); + } + return list; + } } diff --git a/java/45-Jump-game-II.java b/java/45-Jump-game-II.java index 97d1b2a1e..9c4836e9a 100644 --- a/java/45-Jump-game-II.java +++ b/java/45-Jump-game-II.java @@ -1,15 +1,15 @@ class Solution { - public int jump(int[] nums) { - int res=0,r=0,l=0,fur=0; - - while(r> permute(int[] nums) { - List> ans = new ArrayList<>(); - function(ans, nums, 0); - return ans; - } - - public void function(List> ans, int[] arr, int start) { - if (start == arr.length) { - List list = new ArrayList(); - for (int i =0; i> permute(int[] nums) { + List> ans = new ArrayList<>(); + function(ans, nums, 0); + return ans; + } + + public void function(List> ans, int[] arr, int start) { + if (start == arr.length) { + List list = new ArrayList(); + for (int i = 0; i < arr.length; i++) list.add(arr[i]); + ans.add(list); + return; } - - public void swap(int[] arr, int a, int b) { - int temp = arr[a]; - arr[a] = arr[b]; - arr[b] = temp; + + for (int i = start; i < arr.length; i++) { + swap(arr, start, i); + function(ans, arr, start + 1); + swap(arr, start, i); } + } + + public void swap(int[] arr, int a, int b) { + int temp = arr[a]; + arr[a] = arr[b]; + arr[b] = temp; + } } diff --git a/java/48-Rotate-Image.java b/java/48-Rotate-Image.java index d53b84f19..1f9fe8d85 100644 --- a/java/48-Rotate-Image.java +++ b/java/48-Rotate-Image.java @@ -5,30 +5,31 @@ // After Reversal: [[7,4,1],[8,5,2],[9,6,3]] class Solution { - public void rotate(int[][] matrix) { - int N = matrix.length; - transpose(matrix, N); - reverse(matrix, N); - } + public void rotate(int[][] matrix) { + int N = matrix.length; + + transpose(matrix, N); + reverse(matrix, N); + } - void transpose(int[][] matrix, int n) { - for (int i = 0; i < n; i++) { - for (int j = i + 1; j < n; j++) { - int temp = matrix[j][i]; - matrix[j][i] = matrix[i][j]; - matrix[i][j] = temp; - } - } + void transpose(int[][] matrix, int n) { + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + int temp = matrix[j][i]; + matrix[j][i] = matrix[i][j]; + matrix[i][j] = temp; + } } + } - void reverse(int[][] matrix, int n) { - for (int i = 0; i < n; i++) { - for (int j = 0; j < n / 2; j++) { - int temp = matrix[i][j]; - matrix[i][j] = matrix[i][n - 1 - j]; - matrix[i][n - 1 - j] = temp; - } - } + void reverse(int[][] matrix, int n) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n / 2; j++) { + int temp = matrix[i][j]; + matrix[i][j] = matrix[i][n - 1 - j]; + matrix[i][n - 1 - j] = temp; + } } + } } diff --git a/java/49-Group-Anagrams.java b/java/49-Group-Anagrams.java index bee654254..1ab4a6a89 100644 --- a/java/49-Group-Anagrams.java +++ b/java/49-Group-Anagrams.java @@ -1,18 +1,19 @@ class Solution { - public List> groupAnagrams(String[] strs) { - List> res = new ArrayList<>(); - if(strs.length==0) return res; - HashMap> map = new HashMap<>(); - for(String s: strs){ - char[] hash = new char[26]; - for(char c: s.toCharArray()){ - hash[c-'a']++; - } - String key = new String(hash); - map.computeIfAbsent(key, k -> new ArrayList<>()); - map.get(key).add(s); - } - res.addAll(map.values()); - return res; + + public List> groupAnagrams(String[] strs) { + List> res = new ArrayList<>(); + if (strs.length == 0) return res; + HashMap> map = new HashMap<>(); + for (String s : strs) { + char[] hash = new char[26]; + for (char c : s.toCharArray()) { + hash[c - 'a']++; + } + String key = new String(hash); + map.computeIfAbsent(key, k -> new ArrayList<>()); + map.get(key).add(s); } + res.addAll(map.values()); + return res; + } } diff --git a/java/494-Target-Sum.java b/java/494-Target-Sum.java index 4ff826d08..64598742a 100644 --- a/java/494-Target-Sum.java +++ b/java/494-Target-Sum.java @@ -1,18 +1,19 @@ //Brute-force solution (accepted) class Solution { - public int findTargetSumWays(int[] nums, int target) { - return helper(nums, target, nums.length, 0); - } - - public int helper(int[] nums, int target, int n, int temp) { - if (n == 0) { - if (target == temp) return 1; - else return 0; - } - else { - return helper(nums, target-nums[n-1], n-1, temp) + helper(nums, target+nums[n-1], n-1, temp); - } + + public int findTargetSumWays(int[] nums, int target) { + return helper(nums, target, nums.length, 0); + } + + public int helper(int[] nums, int target, int n, int temp) { + if (n == 0) { + if (target == temp) return 1; else return 0; + } else { + return ( + helper(nums, target - nums[n - 1], n - 1, temp) + + helper(nums, target + nums[n - 1], n - 1, temp) + ); } - + } } diff --git a/java/5-Longest-Palindromic-Substring.java b/java/5-Longest-Palindromic-Substring.java index 6230ea425..770892a52 100644 --- a/java/5-Longest-Palindromic-Substring.java +++ b/java/5-Longest-Palindromic-Substring.java @@ -1,43 +1,40 @@ class Solution { - public String longestPalindrome(String s) { - int strLength = s.length(); + public String longestPalindrome(String s) { + int strLength = s.length(); - if (strLength < 2) { - return s; - } - - int resultLength = 0; - String result = ""; - - for (int i = 0; i < s.length(); i++) { - //Odd length - int l = i, r = i; - while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { - if ((r - l + 1) > resultLength) { - result = s.substring(l, r + 1); - resultLength = r - l + 1; - } - l -= 1; - r += 1; - } - - // even length - l = i; - r = i + 1; - while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { - if ((r - l + 1) > resultLength) { - result = s.substring(l, r + 1); - resultLength = r - l + 1; - } - l -= 1; - r += 1; - } + if (strLength < 2) { + return s; + } + int resultLength = 0; + String result = ""; + for (int i = 0; i < s.length(); i++) { + //Odd length + int l = i, r = i; + while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { + if ((r - l + 1) > resultLength) { + result = s.substring(l, r + 1); + resultLength = r - l + 1; } - - return result; - + l -= 1; + r += 1; + } + + // even length + l = i; + r = i + 1; + while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { + if ((r - l + 1) > resultLength) { + result = s.substring(l, r + 1); + resultLength = r - l + 1; + } + l -= 1; + r += 1; + } } -} \ No newline at end of file + + return result; + } +} diff --git a/java/50-Pow(x, n).java b/java/50-Pow(x, n).java index 611f37ee7..6b68586e2 100644 --- a/java/50-Pow(x, n).java +++ b/java/50-Pow(x, n).java @@ -1,30 +1,31 @@ -//Instead of using the classic recursive approach i.e. x*pow(x, n-1) just have (x*x), i.e., pow(x*x, n/2). +//Instead of using the classic recursive approach i.e. x*pow(x, n-1) just have (x*x), i.e., pow(x*x, n/2). //This will make the TC logarithmic instead of linear. //Just take care of the edge cases like Integer.MIN_VALUE, negative power, odd cases. //Asked in Amazon, Meta, Google, Linkedin, Bloomberg class Solution { - public double myPow(double x, int n) { - if (n==0) { - return 1; - } - //Make the negative values positive - else if (n<0) { - //whenever even just divide it by 2 - //this will also include Integer.MIN_VALUE - //We're doing this because if I do -N and N=Integer.MIN_VALUE it'll become a value which is greater than the max value of Integer.MAX_VALUE - if (n%2 == 0) { - n = n/2; - n = -n; - x = (1/x)*(1/x); - } else { //Odds don't need to be divided as their negative is in the positive limit - n = -n; - x = 1/x; - } - } - if (n%2 == 0) { //even - return myPow(x*x, n/2); - } else { //odd - return x*myPow(x*x, n/2); - } + + public double myPow(double x, int n) { + if (n == 0) { + return 1; } + //Make the negative values positive + else if (n < 0) { + //whenever even just divide it by 2 + //this will also include Integer.MIN_VALUE + //We're doing this because if I do -N and N=Integer.MIN_VALUE it'll become a value which is greater than the max value of Integer.MAX_VALUE + if (n % 2 == 0) { + n = n / 2; + n = -n; + x = (1 / x) * (1 / x); + } else { //Odds don't need to be divided as their negative is in the positive limit + n = -n; + x = 1 / x; + } + } + if (n % 2 == 0) { //even + return myPow(x * x, n / 2); + } else { //odd + return x * myPow(x * x, n / 2); + } + } } diff --git a/java/51-N-Queens.java b/java/51-N-Queens.java index 9fe0dd09a..8ee86a023 100644 --- a/java/51-N-Queens.java +++ b/java/51-N-Queens.java @@ -1,57 +1,57 @@ class Solution { - public List> solveNQueens(int n) { - List> ans = new ArrayList>(); - boolean[][] board = new boolean[n][n]; - queens(board, 0, ans); - return ans; - + + public List> solveNQueens(int n) { + List> ans = new ArrayList>(); + boolean[][] board = new boolean[n][n]; + queens(board, 0, ans); + return ans; + } + + public void queens(boolean[][] board, int row, List> ans2) { + //base case + if (row == board.length) { + ArrayList ans = new ArrayList(); + createAnswer(board, ans); + ans2.add(ans); + return; } - - public void queens(boolean[][] board, int row , List> ans2) { - //base case - if (row == board.length) { - ArrayList ans = new ArrayList(); - createAnswer(board, ans); - ans2.add(ans); - return; - } - for (int col = 0; col ans) { - for (int i = 0; i ans) { + for (int i = 0; i < board.length; i++) { + StringBuilder str = new StringBuilder(); + for (int j = 0; j < board[0].length; j++) { + if (board[i][j]) { + str.append("Q"); + } else str.append("."); + } + ans.add(str.toString()); } - - public boolean isSafe(boolean[][] board, int row, int col) { - for (int i = 0; i spiralOrder(int[][] matrix) { - List list = new ArrayList<>(); - int rb = 0; - int re = matrix.length - 1; - int cb = 0; - int ce = matrix[0].length - 1; - - while (rb <= re && cb <= ce) { - for (int j = cb; j <= ce; j++) { - list.add(matrix[rb][j]); - } - rb++; - - for (int i = rb; i <= re; i++) { - list.add(matrix[i][ce]); - } - ce--; - - if (rb <= re) { - for (int j = ce; j >= cb; j--) { - list.add(matrix[re][j]); - } - } - re--; - - if (cb <= ce) { - for (int i = re; i >= rb; i--) { - list.add(matrix[i][cb]); - } - } - cb++; + + public List spiralOrder(int[][] matrix) { + List list = new ArrayList<>(); + int rb = 0; + int re = matrix.length - 1; + int cb = 0; + int ce = matrix[0].length - 1; + + while (rb <= re && cb <= ce) { + for (int j = cb; j <= ce; j++) { + list.add(matrix[rb][j]); + } + rb++; + + for (int i = rb; i <= re; i++) { + list.add(matrix[i][ce]); + } + ce--; + + if (rb <= re) { + for (int j = ce; j >= cb; j--) { + list.add(matrix[re][j]); } - - return list; + } + re--; + + if (cb <= ce) { + for (int i = re; i >= rb; i--) { + list.add(matrix[i][cb]); + } + } + cb++; } + + return list; + } } diff --git a/java/543-Diameter-of-Binary-Tree.java b/java/543-Diameter-of-Binary-Tree.java index cac07b11e..ecf2df0eb 100644 --- a/java/543-Diameter-of-Binary-Tree.java +++ b/java/543-Diameter-of-Binary-Tree.java @@ -1,18 +1,19 @@ class Solution { - int result = -1; - public int diameterOfBinaryTree(TreeNode root) { - dfs(root); - return result; - } + int result = -1; + + public int diameterOfBinaryTree(TreeNode root) { + dfs(root); + return result; + } - private int dfs(TreeNode current) { - if (current == null) { - return -1; - } - int left = 1 + dfs(current.left); - int right = 1 + dfs(current.right); - result = Math.max(result, (left + right)); - return Math.max(left, right); + private int dfs(TreeNode current) { + if (current == null) { + return -1; } + int left = 1 + dfs(current.left); + int right = 1 + dfs(current.right); + result = Math.max(result, (left + right)); + return Math.max(left, right); + } } diff --git a/java/55-Jump-Game.java b/java/55-Jump-Game.java index e8475fa87..5b0c88d7b 100644 --- a/java/55-Jump-Game.java +++ b/java/55-Jump-Game.java @@ -1,12 +1,12 @@ class Solution { - public boolean canJump(int[] nums) { - int goal = nums.length-1; - for (int i = nums.length-2; i >= 0; i--) { - if (nums[i] + i >= goal) { - goal = i; - } - } - return goal == 0; + + public boolean canJump(int[] nums) { + int goal = nums.length - 1; + for (int i = nums.length - 2; i >= 0; i--) { + if (nums[i] + i >= goal) { + goal = i; + } } + return goal == 0; + } } - diff --git a/java/56-Merge-Intervals.java b/java/56-Merge-Intervals.java index cd9cb6c6c..1f97c0197 100644 --- a/java/56-Merge-Intervals.java +++ b/java/56-Merge-Intervals.java @@ -1,21 +1,23 @@ class Solution { - public int[][] merge(int[][] intervals) { - ArrayList ans = new ArrayList<>(); - Arrays.sort(intervals, (a,b) -> Integer.compare(a[0], b[0])); - ans.add(intervals[0]); - for (int i = 1; i ans = new ArrayList<>(); + Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); + ans.add(intervals[0]); + for (int i = 1; i < intervals.length; i++) { + int prevStart = ans.get(ans.size() - 1)[0]; + //comparing the values of prevEnd and curEnd + int curStart = intervals[i][0]; + if (curStart <= ans.get(ans.size() - 1)[1]) { + //do the merging + ans.get(ans.size() - 1)[1] = + Math.max(ans.get(ans.size() - 1)[1], intervals[i][1]); + } else { + ans.add(intervals[i]); + } } + int[][] res = new int[ans.size()][2]; + ans.toArray(res); + return res; + } } diff --git a/java/567-Permutation-in-String.java b/java/567-Permutation-in-String.java index 0e55f7f21..89a88a9fd 100644 --- a/java/567-Permutation-in-String.java +++ b/java/567-Permutation-in-String.java @@ -1,34 +1,34 @@ class Solution { - public boolean checkInclusion(String s1, String s2) { - if (s2.length() res = new ArrayList<>(); - for (int[] interval: intervals) { - if (newInterval==null || interval[1]newInterval[1]) { - res.add(newInterval); - res.add(interval); - newInterval = null; - } - else { - newInterval[0] = Math.min(interval[0], newInterval[0]); - newInterval[1] = Math.max(interval[1], newInterval[1]); - } - } - if (newInterval!=null) res.add(newInterval); - return res.toArray(new int[res.size()][]); + + public int[][] insert(int[][] intervals, int[] newInterval) { + List res = new ArrayList<>(); + for (int[] interval : intervals) { + if (newInterval == null || interval[1] < newInterval[0]) res.add( + interval + ); else if (interval[0] > newInterval[1]) { + res.add(newInterval); + res.add(interval); + newInterval = null; + } else { + newInterval[0] = Math.min(interval[0], newInterval[0]); + newInterval[1] = Math.max(interval[1], newInterval[1]); + } } + if (newInterval != null) res.add(newInterval); + return res.toArray(new int[res.size()][]); + } } diff --git a/java/572-Subtree-of-Another-Tree.java b/java/572-Subtree-of-Another-Tree.java index 747a98b3f..a7ac1e08b 100644 --- a/java/572-Subtree-of-Another-Tree.java +++ b/java/572-Subtree-of-Another-Tree.java @@ -1,11 +1,15 @@ class Solution { - public boolean isSubtree(TreeNode root, TreeNode subRoot) { - if (root == null && subRoot == null) return true; - if (root == null || subRoot == null) return false; - if (root.val == subRoot.val) { - return (isSubtree(root.left, subRoot.left) && isSubtree(root.right, subRoot.right)); - } else { - return (isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot)); - } + + public boolean isSubtree(TreeNode root, TreeNode subRoot) { + if (root == null && subRoot == null) return true; + if (root == null || subRoot == null) return false; + if (root.val == subRoot.val) { + return ( + isSubtree(root.left, subRoot.left) && + isSubtree(root.right, subRoot.right) + ); + } else { + return (isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot)); } + } } diff --git a/java/6-Zigzag-Conversion.java b/java/6-Zigzag-Conversion.java index a9f2d52f3..7e7c72314 100644 --- a/java/6-Zigzag-Conversion.java +++ b/java/6-Zigzag-Conversion.java @@ -1,31 +1,32 @@ //We check whether we are at the diagonal or not using a boolean and increment the pointer accordingly. class Solution { - public String convert(String s, int row) { - if (row==1) return s; - StringBuilder sb = new StringBuilder(); - for (int i = 0; i list = new ArrayList<>(); - for (int i = 1; i list = new ArrayList<>(); + for (int i = 1; i < n; i++) { + fact = fact * i; + list.add(i); } - - { - //Bruteforce solution (gives TLE) similar to Next Permutation problem no.31 - -// public String getPermutation(int n, int k) { -// int[] num = new int[n]; -// for (int i = 1; i<=n; i++) { -// num[i-1] = i; -// } -// for (int i = 1; i0 && nums[pivot]0 && nums[j]0 && nums[pivot]0 && nums[j]= 0; i--) { - for (int j = n - 2; j >= 0; j--) { - dp[i][j] = dp[i][j + 1] + dp[i + 1][j]; - } - } - return dp[0][0]; - } - } \ No newline at end of file + + public static int uniquePaths(int m, int n) { + int[][] dp = new int[m][n]; + + // Fill out last row + for (int j = 0; j < n; j++) { + dp[m - 1][j] = 1; + } + + // Fill out last column + for (int i = 0; i < m; i++) { + dp[i][n - 1] = 1; + } + + for (int i = m - 2; i >= 0; i--) { + for (int j = n - 2; j >= 0; j--) { + dp[i][j] = dp[i][j + 1] + dp[i + 1][j]; + } + } + return dp[0][0]; + } +} diff --git a/java/621-Task-Scheduler.java b/java/621-Task-Scheduler.java index 3141671d0..fa6f074eb 100644 --- a/java/621-Task-Scheduler.java +++ b/java/621-Task-Scheduler.java @@ -1,28 +1,26 @@ class Solution { - public int leastInterval(char[] tasks, int n) { - if (n==0) return tasks.length; - PriorityQueue pq = new PriorityQueue<>((a,b)->b-a); - Queue> q = new LinkedList<>(); - int[] arr = new int[26]; - for (char c: tasks) - arr[c-'A']++; - for (int val: arr) - if (val>0) - pq.add(val); - int time = 0; - // System.out.println(pq); - // System.out.println(q); - while ((!pq.isEmpty() || !q.isEmpty())) { - if (pq.isEmpty()) { - time = Math.max(q.peek().getValue(), time); - pq.add(q.poll().getKey()); - } - int val = pq.poll(); - val--; - time++; - if (val>0) q.add(new Pair(val, time+n)); -// System.out.println(q + " "+ time); - } - return time; + + public int leastInterval(char[] tasks, int n) { + if (n == 0) return tasks.length; + PriorityQueue pq = new PriorityQueue<>((a, b) -> b - a); + Queue> q = new LinkedList<>(); + int[] arr = new int[26]; + for (char c : tasks) arr[c - 'A']++; + for (int val : arr) if (val > 0) pq.add(val); + int time = 0; + // System.out.println(pq); + // System.out.println(q); + while ((!pq.isEmpty() || !q.isEmpty())) { + if (pq.isEmpty()) { + time = Math.max(q.peek().getValue(), time); + pq.add(q.poll().getKey()); + } + int val = pq.poll(); + val--; + time++; + if (val > 0) q.add(new Pair(val, time + n)); + // System.out.println(q + " "+ time); } + return time; + } } diff --git a/java/63-Unique-Paths-II.java b/java/63-Unique-Paths-II.java index c0226e9b3..979640393 100644 --- a/java/63-Unique-Paths-II.java +++ b/java/63-Unique-Paths-II.java @@ -1,23 +1,30 @@ //Same as unique paths 1 just one extra condition to return 0 if grid[i][j] == 1 class Solution { - public int uniquePathsWithObstacles(int[][] grid) { - return dfs(grid, 0, 0, grid.length, grid[0].length, new int[grid.length][grid[0].length]); + + public int uniquePathsWithObstacles(int[][] grid) { + return dfs( + grid, + 0, + 0, + grid.length, + grid[0].length, + new int[grid.length][grid[0].length] + ); + } + + public int dfs(int[][] grid, int i, int j, int m, int n, int[][] dp) { + if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == 1) { + return 0; } - - public int dfs(int[][] grid, int i, int j, int m, int n, int[][] dp) { - if (i<0 || j<0 || i>=m || j>=n || grid[i][j]==1) { - return 0; - } - if (i==m-1 && j==n-1) { - dp[i][j] = 1; - return dp[i][j]; - } - if (dp[i][j]!=0) return dp[i][j]; - int right = dfs(grid, i, j+1, m, n, dp); - int left = dfs(grid, i+1, j, m, n, dp); - dp[i][j] = right+left; - return dp[i][j]; + if (i == m - 1 && j == n - 1) { + dp[i][j] = 1; + return dp[i][j]; } - + if (dp[i][j] != 0) return dp[i][j]; + int right = dfs(grid, i, j + 1, m, n, dp); + int left = dfs(grid, i + 1, j, m, n, dp); + dp[i][j] = right + left; + return dp[i][j]; + } } diff --git a/java/637-Average-of-Levels-in-Binary-Tree.java b/java/637-Average-of-Levels-in-Binary-Tree.java index 1259fda29..3554c8d5c 100644 --- a/java/637-Average-of-Levels-in-Binary-Tree.java +++ b/java/637-Average-of-Levels-in-Binary-Tree.java @@ -1,23 +1,22 @@ //Apply Breadth first search. //Asked in Amazon and Meta class Solution { - public List averageOfLevels(TreeNode root) { - List ans = new ArrayList<>(); - Queue q = new LinkedList(); - q.offer(root); - while (!q.isEmpty()) { - int queue_size = q.size(); - double avg = 0; - for (int i = 0; i averageOfLevels(TreeNode root) { + List ans = new ArrayList<>(); + Queue q = new LinkedList(); + q.offer(root); + while (!q.isEmpty()) { + int queue_size = q.size(); + double avg = 0; + for (int i = 0; i < queue_size; i++) { + TreeNode cur = q.poll(); + avg += cur.val; + if (cur.left != null) q.offer(cur.left); + if (cur.right != null) q.offer(cur.right); + } + ans.add(avg / queue_size); } + return ans; + } } diff --git a/java/64-Minimum-Path-Sum.java b/java/64-Minimum-Path-Sum.java index c31a1cd71..30020dad3 100644 --- a/java/64-Minimum-Path-Sum.java +++ b/java/64-Minimum-Path-Sum.java @@ -1,27 +1,29 @@ class Solution { - public int minPathSum(int[][] grid) { - int m = grid.length-1; - int n = grid[0].length-1; - int[][] dp = new int[m+1][n+1]; - for (int[] arr: dp) { - Arrays.fill(arr, -1); - } - return helper(grid, m, n, dp); + + public int minPathSum(int[][] grid) { + int m = grid.length - 1; + int n = grid[0].length - 1; + int[][] dp = new int[m + 1][n + 1]; + for (int[] arr : dp) { + Arrays.fill(arr, -1); } - - public int helper(int[][] grid,int m, int n, int[][] dp) { - if (m==0 && n==0) return grid[0][0]; - if (m==0) { - dp[m][n] = grid[m][n] + helper(grid, m, n-1, dp); - return dp[m][n]; - } - if (n==0) { - dp[m][n] = grid[m][n] + helper(grid, m-1, n, dp); - return dp[m][n]; - } - if (dp[m][n]!=-1) return dp[m][n]; - dp[m][n] = grid[m][n]+Math.min(helper(grid,m, n-1, dp), helper(grid, m-1, n, dp)); - return dp[m][n]; + return helper(grid, m, n, dp); + } + + public int helper(int[][] grid, int m, int n, int[][] dp) { + if (m == 0 && n == 0) return grid[0][0]; + if (m == 0) { + dp[m][n] = grid[m][n] + helper(grid, m, n - 1, dp); + return dp[m][n]; } - + if (n == 0) { + dp[m][n] = grid[m][n] + helper(grid, m - 1, n, dp); + return dp[m][n]; + } + if (dp[m][n] != -1) return dp[m][n]; + dp[m][n] = + grid[m][n] + + Math.min(helper(grid, m, n - 1, dp), helper(grid, m - 1, n, dp)); + return dp[m][n]; + } } diff --git a/java/647-Palindromic-Substrings.java b/java/647-Palindromic-Substrings.java index f636cafdb..943eb2600 100644 --- a/java/647-Palindromic-Substrings.java +++ b/java/647-Palindromic-Substrings.java @@ -1,27 +1,31 @@ class Solution { - public int countSubstrings(String s) { - if (s.length() < 2) { - return s.length(); - } - int result = 0; - for (int i = 0; i < s.length(); i++) { - // Odd Length - int left = i, right = i; - while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { - result++; - left--; - right++; - } - // Even Length - left = i; - right = i + 1; - while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { - result++; - left--; - right++; - } - } - return result; + public int countSubstrings(String s) { + if (s.length() < 2) { + return s.length(); } -} \ No newline at end of file + int result = 0; + for (int i = 0; i < s.length(); i++) { + // Odd Length + int left = i, right = i; + while ( + left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right) + ) { + result++; + left--; + right++; + } + // Even Length + left = i; + right = i + 1; + while ( + left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right) + ) { + result++; + left--; + right++; + } + } + return result; + } +} diff --git a/java/66-Plus-One.java b/java/66-Plus-One.java index 518cc01e8..a7eca484b 100644 --- a/java/66-Plus-One.java +++ b/java/66-Plus-One.java @@ -1,29 +1,29 @@ class Solution { - public int[] plusOne(int[] digits) { - final int len = digits.length; - int[] newDigits = new int[len + 1]; - int carry = 1; - int currSum = 0; - for (int i = len - 1; i >= 0; i--) { - currSum = digits[i] + carry; - if(currSum > 9) { - digits[i] = currSum % 10; - newDigits[i + 1] = digits[i]; - carry = 1; - } else { - digits[i] = currSum; - newDigits[i + 1] = digits[i]; - carry = 0; - break; - } - } - - if(carry == 1) { - newDigits[0] = 1; - return newDigits; - } + public int[] plusOne(int[] digits) { + final int len = digits.length; + int[] newDigits = new int[len + 1]; + int carry = 1; + int currSum = 0; + for (int i = len - 1; i >= 0; i--) { + currSum = digits[i] + carry; + if (currSum > 9) { + digits[i] = currSum % 10; + newDigits[i + 1] = digits[i]; + carry = 1; + } else { + digits[i] = currSum; + newDigits[i + 1] = digits[i]; + carry = 0; + break; + } + } - return digits; + if (carry == 1) { + newDigits[0] = 1; + return newDigits; } -} \ No newline at end of file + + return digits; + } +} diff --git a/java/662-Maximum-Width-of-Binary-Tree.java b/java/662-Maximum-Width-of-Binary-Tree.java index 2df7d035f..92fcd377b 100644 --- a/java/662-Maximum-Width-of-Binary-Tree.java +++ b/java/662-Maximum-Width-of-Binary-Tree.java @@ -2,24 +2,23 @@ //This video helped https://www.youtube.com/watch?v=ZbybYvcVLks&ab_channel=takeUforward class Solution { - public int widthOfBinaryTree(TreeNode root) { - Queue> q = new LinkedList<>(); - int maxWidth = 0; - q.offer(new Pair(root, 1)); - while (!q.isEmpty()) { - int l = q.peek().getValue(); - int r = l; - int size = q.size(); - for (int i = 0; i> q = new LinkedList<>(); + int maxWidth = 0; + q.offer(new Pair(root, 1)); + while (!q.isEmpty()) { + int l = q.peek().getValue(); + int r = l; + int size = q.size(); + for (int i = 0; i < size; i++) { + TreeNode cur = q.peek().getKey(); + r = q.poll().getValue(); + if (cur.left != null) q.offer(new Pair(cur.left, 2 * r)); + if (cur.right != null) q.offer(new Pair(cur.right, 2 * r + 1)); + } + maxWidth = Math.max(maxWidth, r - l + 1); } + return maxWidth; + } } diff --git a/java/695-Max-Area-of-Island.java b/java/695-Max-Area-of-Island.java index f42ec4bbc..f7ffa6d30 100644 --- a/java/695-Max-Area-of-Island.java +++ b/java/695-Max-Area-of-Island.java @@ -1,27 +1,26 @@ class Solution { - public int maxAreaOfIsland(int[][] grid) { - int ans = 0; - int m = grid.length; - int n = grid[0].length; - for (int i = 0; i=m || j>=n || grid[i][j] == 0) - return count[0]; - count[0]++; - grid[i][j] = 0; - dfs(grid, i-1, j, m, n, count); - dfs(grid, i+1, j, m, n, count); - dfs(grid, i, j-1, m, n, count); - dfs(grid, i, j+1, m, n, count); - return count[0]; - } - + return ans; + } + + public int dfs(int[][] grid, int i, int j, int m, int n, int[] count) { + if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == 0) return count[0]; + count[0]++; + grid[i][j] = 0; + dfs(grid, i - 1, j, m, n, count); + dfs(grid, i + 1, j, m, n, count); + dfs(grid, i, j - 1, m, n, count); + dfs(grid, i, j + 1, m, n, count); + return count[0]; + } } diff --git a/java/7-Reverse-Integer.java b/java/7-Reverse-Integer.java index 74c399e17..6f9da3d75 100644 --- a/java/7-Reverse-Integer.java +++ b/java/7-Reverse-Integer.java @@ -1,26 +1,21 @@ class Solution { - public int reverse(int x) { - - int min = Integer.MIN_VALUE; - int max = Integer.MAX_VALUE; - - - int res = 0; - while(x!=0){ - int digit = x % 10; - x = x / 10; - - if((res> max / 10) || (res == max / 10 && digit >= max % 10)) - return 0; - - if((res < min / 10) || (res== min / 10 && digit <= min % 10)) - return 0; - - - res = (res * 10) + digit; - } - - return res; - + + public int reverse(int x) { + int min = Integer.MIN_VALUE; + int max = Integer.MAX_VALUE; + + int res = 0; + while (x != 0) { + int digit = x % 10; + x = x / 10; + + if ((res > max / 10) || (res == max / 10 && digit >= max % 10)) return 0; + + if ((res < min / 10) || (res == min / 10 && digit <= min % 10)) return 0; + + res = (res * 10) + digit; } + + return res; + } } diff --git a/java/70-Climbing-Stairs.java b/java/70-Climbing-Stairs.java index eab7a260e..592211859 100644 --- a/java/70-Climbing-Stairs.java +++ b/java/70-Climbing-Stairs.java @@ -1,51 +1,54 @@ //optimal class Solution { - public int climbStairs(int n) { - int a = 1; - int b = 1; - int c; - - for (int i = 0; i < n - 1; i++) { - c = a + b; - a = b; - b = c; - } - return b; + + public int climbStairs(int n) { + int a = 1; + int b = 1; + int c; + + for (int i = 0; i < n - 1; i++) { + c = a + b; + a = b; + b = c; } + return b; + } } //bottom up class Solution { - public int climbStairs(int n) { - int[] dp = new int[n + 1]; - dp[0] = 1; - dp[1] = 1; - - for (int i = 2; i < n + 1; i++) { - dp[i] = dp[i - 1] + dp[i - 2]; - } - return dp[n]; + + public int climbStairs(int n) { + int[] dp = new int[n + 1]; + dp[0] = 1; + dp[1] = 1; + + for (int i = 2; i < n + 1; i++) { + dp[i] = dp[i - 1] + dp[i - 2]; } + return dp[n]; + } } //top down with memo[] class Solution { - public int climbStairs(int n) { - int[] memo = new int[n + 1]; - Arrays.fill(memo, -1); - - return climbStairs(n - 1, memo) + climbStairs(n - 2, memo); - } - - private int climbStairs(int n, int[] memo) { - if (n < 0) return 0; - if (n == 0 || n == 1) { - memo[n] = 1; - return memo[n]; - } - if (memo[n] != -1) return memo[n]; - - memo[n] = climbStairs(n - 1, memo) + climbStairs(n - 2, memo); - return memo[n]; + + public int climbStairs(int n) { + int[] memo = new int[n + 1]; + Arrays.fill(memo, -1); + + return climbStairs(n - 1, memo) + climbStairs(n - 2, memo); + } + + private int climbStairs(int n, int[] memo) { + if (n < 0) return 0; + if (n == 0 || n == 1) { + memo[n] = 1; + return memo[n]; } -} \ No newline at end of file + if (memo[n] != -1) return memo[n]; + + memo[n] = climbStairs(n - 1, memo) + climbStairs(n - 2, memo); + return memo[n]; + } +} diff --git a/java/703-Kth-Largest-Element-in-a-Stream.java b/java/703-Kth-Largest-Element-in-a-Stream.java index 83b73cfca..4ca5455b0 100644 --- a/java/703-Kth-Largest-Element-in-a-Stream.java +++ b/java/703-Kth-Largest-Element-in-a-Stream.java @@ -1,18 +1,19 @@ class KthLargest { - final PriorityQueue heap = new PriorityQueue<>(); - final int k; - public KthLargest(int k, int[] nums) { - this.k = k; - for (int n: nums) add(n); - } - - public int add(int val) { - if (heap.size()heap.peek()) { - heap.poll();//remove the top element - heap.add(val);//add the new element - } - return heap.peek(); + final PriorityQueue heap = new PriorityQueue<>(); + final int k; + + public KthLargest(int k, int[] nums) { + this.k = k; + for (int n : nums) add(n); + } + + public int add(int val) { + if (heap.size() < k) heap.offer(val); //for adding the values of the array + else if (val > heap.peek()) { + heap.poll(); //remove the top element + heap.add(val); //add the new element } + return heap.peek(); + } } diff --git a/java/704-Binary-Search.java b/java/704-Binary-Search.java index cda423821..6ed527186 100644 --- a/java/704-Binary-Search.java +++ b/java/704-Binary-Search.java @@ -1,17 +1,16 @@ class Solution { - public int search(int[] nums, int target) { - - int i = 0; - int j = nums.length-1; - - while(i<=j){ - int mid = (i+j)/2; - - if(nums[mid] == target) return mid; - else if(nums[mid]=k) product/=nums[left++]; - ans += right-left+1; - } - return ans; + + public int numSubarrayProductLessThanK(int[] nums, int k) { + if (k <= 1) return 0; + int left = 0; + int product = 1; + int ans = 0; + for (int right = 0; right < nums.length; right++) { + product *= nums[right]; + while (product >= k) product /= nums[left++]; + ans += right - left + 1; } + return ans; + } } diff --git a/java/72-Edit-Distance.java b/java/72-Edit-Distance.java index 6e7bc8b4b..835209355 100644 --- a/java/72-Edit-Distance.java +++ b/java/72-Edit-Distance.java @@ -3,41 +3,41 @@ //Memoized code class Solution { - public int minDistance(String word1, String word2) { - int m = word1.length()-1; - int n = word2.length()-1; - int[][] dp = new int[m+2][n+2]; - for (int[] d: dp) { - Arrays.fill(d, -1); - } - return helper(word1, word2, m, n, dp); + + public int minDistance(String word1, String word2) { + int m = word1.length() - 1; + int n = word2.length() - 1; + int[][] dp = new int[m + 2][n + 2]; + for (int[] d : dp) { + Arrays.fill(d, -1); + } + return helper(word1, word2, m, n, dp); + } + + public int helper(String word1, String word2, int m, int n, int[][] dp) { + //the strings are null + if (m + 1 == 0 && n + 1 == 0) { + return 0; + } + //one of the strings are null + if (m + 1 == 0 || n + 1 == 0) { + return Math.max(m + 1, n + 1); } - - public int helper(String word1, String word2, int m, int n, int[][] dp) { - //the strings are null - if (m+1==0 && n+1==0) { - return 0; - } - //one of the strings are null - if (m+1==0 || n+1==0) { - return Math.max(m+1, n+1); - } - //both values at the index are equal - if (dp[m][n]!=-1) return dp[m][n]; - if (word1.charAt(m)==word2.charAt(n)) { - dp[m][n] = helper(word1, word2, m-1, n-1, dp); - return dp[m][n]; - } - else { - //try deletion - int delete = 1+helper(word1, word2, m-1, n, dp); - //try insertion - int insert = 1+helper(word1, word2, m, n-1, dp); - //try replacing - int replace = 1+helper(word1, word2, m-1, n-1, dp); - //now we'll choose the minimum out of these 3 and add 1 for the operation cost - dp[m][n] = Math.min(Math.min(delete, insert), replace); - return dp[m][n]; - } + //both values at the index are equal + if (dp[m][n] != -1) return dp[m][n]; + if (word1.charAt(m) == word2.charAt(n)) { + dp[m][n] = helper(word1, word2, m - 1, n - 1, dp); + return dp[m][n]; + } else { + //try deletion + int delete = 1 + helper(word1, word2, m - 1, n, dp); + //try insertion + int insert = 1 + helper(word1, word2, m, n - 1, dp); + //try replacing + int replace = 1 + helper(word1, word2, m - 1, n - 1, dp); + //now we'll choose the minimum out of these 3 and add 1 for the operation cost + dp[m][n] = Math.min(Math.min(delete, insert), replace); + return dp[m][n]; } + } } diff --git a/java/73-Set-Matrix-Zeroes.java b/java/73-Set-Matrix-Zeroes.java index c23ef668b..894253318 100644 --- a/java/73-Set-Matrix-Zeroes.java +++ b/java/73-Set-Matrix-Zeroes.java @@ -1,40 +1,41 @@ class Solution { - public void setZeroes(int[][] matrix) { - int rows = matrix.length; - int cols = matrix[0].length; - boolean firstRow = false; - - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { - if (matrix[i][j] == 0) { - matrix[0][j] = 0; - if (i == 0) { - firstRow = true; - } else { - matrix[i][0] = 0; - } - } - } + + public void setZeroes(int[][] matrix) { + int rows = matrix.length; + int cols = matrix[0].length; + boolean firstRow = false; + + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + if (matrix[i][j] == 0) { + matrix[0][j] = 0; + if (i == 0) { + firstRow = true; + } else { + matrix[i][0] = 0; + } } - - for (int i = 1; i < rows; i++) { - for (int j = 1; j < cols; j++) { - if (matrix[0][j] == 0 || matrix[i][0] == 0) { - matrix[i][j] = 0; - } - } - } - - if (matrix[0][0] == 0) { - for (int i = 0; i < rows; i++) { - matrix[i][0] = 0; - } - } - - if (firstRow) { - for (int j = 0; j < cols; j++) { - matrix[0][j] = 0; - } + } + } + + for (int i = 1; i < rows; i++) { + for (int j = 1; j < cols; j++) { + if (matrix[0][j] == 0 || matrix[i][0] == 0) { + matrix[i][j] = 0; } + } + } + + if (matrix[0][0] == 0) { + for (int i = 0; i < rows; i++) { + matrix[i][0] = 0; + } + } + + if (firstRow) { + for (int j = 0; j < cols; j++) { + matrix[0][j] = 0; + } } + } } diff --git a/java/739-Daily-Temperatures.java b/java/739-Daily-Temperatures.java index db979d3ea..737cebba6 100644 --- a/java/739-Daily-Temperatures.java +++ b/java/739-Daily-Temperatures.java @@ -1,14 +1,17 @@ class Solution { - public int[] dailyTemperatures(int[] temperatures) { - int[] ans = new int[temperatures.length]; - Stack stack = new Stack<>(); - for (int currDay = 0; currDaytemperatures[stack.peek()]) { - int prevDay = stack.pop(); - ans[prevDay] = currDay-prevDay; - } - stack.add(currDay); - } - return ans; + + public int[] dailyTemperatures(int[] temperatures) { + int[] ans = new int[temperatures.length]; + Stack stack = new Stack<>(); + for (int currDay = 0; currDay < temperatures.length; currDay++) { + while ( + !stack.isEmpty() && temperatures[currDay] > temperatures[stack.peek()] + ) { + int prevDay = stack.pop(); + ans[prevDay] = currDay - prevDay; + } + stack.add(currDay); } + return ans; + } } diff --git a/java/74-Search-A-2D-Matrix.java b/java/74-Search-A-2D-Matrix.java index 4d20d3593..f7690cd00 100644 --- a/java/74-Search-A-2D-Matrix.java +++ b/java/74-Search-A-2D-Matrix.java @@ -1,22 +1,19 @@ class Solution { - public boolean searchMatrix(int[][] matrix, int target) { - int lrow = 0; - int rrow = matrix.length - 1; - int n = 0; - while (lrow < rrow) { - n = (lrow + rrow) / 2; - if (matrix[n][0] > target) - rrow = n; - else if (matrix[n][matrix[0].length - 1] < target) - lrow = n + 1; - else - break; - } + public boolean searchMatrix(int[][] matrix, int target) { + int lrow = 0; + int rrow = matrix.length - 1; + int n = 0; - if (Arrays.binarySearch(matrix[(lrow + rrow) / 2], target) >= 0) - return true; - else - return false; + while (lrow < rrow) { + n = (lrow + rrow) / 2; + if (matrix[n][0] > target) rrow = n; else if ( + matrix[n][matrix[0].length - 1] < target + ) lrow = n + 1; else break; } -} \ No newline at end of file + + if ( + Arrays.binarySearch(matrix[(lrow + rrow) / 2], target) >= 0 + ) return true; else return false; + } +} diff --git a/java/746-Min-Cost-Climbing-Stairs.java b/java/746-Min-Cost-Climbing-Stairs.java index 3ee52b21a..9a5ef4632 100644 --- a/java/746-Min-Cost-Climbing-Stairs.java +++ b/java/746-Min-Cost-Climbing-Stairs.java @@ -1,13 +1,15 @@ class Solution { - public int minCostClimbingStairs(int[] cost) { - int[] res = new int[cost.length + 1]; - res[cost.length] = 0; - res[cost.length - 1] = cost[cost.length - 1]; - - for(int i = cost.length - 2; i >= 0; i--){ - res[i] = (res[i+1] < res[i+2]) ? res[i+1] + cost[i] : res[i+2] + cost[i]; - } - - return Math.min(res[0] , res[1]); + + public int minCostClimbingStairs(int[] cost) { + int[] res = new int[cost.length + 1]; + res[cost.length] = 0; + res[cost.length - 1] = cost[cost.length - 1]; + + for (int i = cost.length - 2; i >= 0; i--) { + res[i] = + (res[i + 1] < res[i + 2]) ? res[i + 1] + cost[i] : res[i + 2] + cost[i]; } + + return Math.min(res[0], res[1]); + } } diff --git a/java/75-Sort-Colors.java b/java/75-Sort-Colors.java index c5a03ffa6..dde074d6d 100644 --- a/java/75-Sort-Colors.java +++ b/java/75-Sort-Colors.java @@ -1,21 +1,20 @@ class Solution { - public void sortColors(int[] nums) { - int left = 0, mid = 0, right = nums.length-1; - while (mid<=right) { - System.out.println(nums[mid]); - if (nums[mid]==1) mid++; - else if (nums[mid]==0) { - swap(nums, mid++, left++); - } else if (nums[mid]==2) { - swap(nums, mid, right--); - } - } + + public void sortColors(int[] nums) { + int left = 0, mid = 0, right = nums.length - 1; + while (mid <= right) { + System.out.println(nums[mid]); + if (nums[mid] == 1) mid++; else if (nums[mid] == 0) { + swap(nums, mid++, left++); + } else if (nums[mid] == 2) { + swap(nums, mid, right--); + } } - - public void swap(int[] nums, int i, int j) { - int temp = nums[i]; - nums[i] = nums[j]; - nums[j] = temp; - } - + } + + public void swap(int[] nums, int i, int j) { + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } } diff --git a/java/752-Open-the-lock.java b/java/752-Open-the-lock.java index 0ab3c6bd4..c505f0583 100644 --- a/java/752-Open-the-lock.java +++ b/java/752-Open-the-lock.java @@ -1,48 +1,48 @@ //Simple BFS solution class Solution { - public int openLock(String[] deadends, String target) { - String start = "0000"; - int ans = 0; - Queue q = new LinkedList<>(); - HashSet visited = new HashSet<>(); - //Add all the deadends in the visited set so we can ignore them and visited values altogether. - for (String s: deadends) - visited.add(s); - q.offer(start); - while (!q.isEmpty()) { - int size = q.size(); - for (int j = 0; j q = new LinkedList<>(); + HashSet visited = new HashSet<>(); + //Add all the deadends in the visited set so we can ignore them and visited values altogether. + for (String s : deadends) visited.add(s); + q.offer(start); + while (!q.isEmpty()) { + int size = q.size(); + for (int j = 0; j < size; j++) { + String str = q.poll(); + StringBuilder cur = new StringBuilder(str); + if (str.equals(target)) return ans; + if (!visited.contains(cur.toString())) { + for (int i = 0; i < start.length(); i++) { + //edge case for 0 + if (cur.charAt(i) == '0') { + cur.setCharAt(i, '1'); + q.offer(cur.toString()); + cur.setCharAt(i, '9'); + q.offer(cur.toString()); + } else if (cur.charAt(i) == '9') { //edge case for 9 + cur.setCharAt(i, '0'); + q.offer(cur.toString()); + cur.setCharAt(i, '8'); + q.offer(cur.toString()); + } else { + cur.setCharAt(i, ((char) (cur.charAt(i) + 1))); + q.offer(cur.toString()); + cur.setCharAt(i, ((char) (cur.charAt(i) - 2))); + q.offer(cur.toString()); } - ans++; + visited.add(str); + cur.setLength(0); + cur.append(str); + } } - return -1; + } + ans++; } + return -1; + } } diff --git a/java/76-Minimum-Window-Substring.java b/java/76-Minimum-Window-Substring.java index f723e2973..b530f6309 100644 --- a/java/76-Minimum-Window-Substring.java +++ b/java/76-Minimum-Window-Substring.java @@ -1,35 +1,36 @@ class Solution { - //sliding window - public String minWindow(String s, String t) { - HashMap map = new HashMap<>(); - for (char x : t.toCharArray()) { - map.put(x, map.getOrDefault(x, 0) + 1); - } + //sliding window + public String minWindow(String s, String t) { + HashMap map = new HashMap<>(); + + for (char x : t.toCharArray()) { + map.put(x, map.getOrDefault(x, 0) + 1); + } - int matched = 0; - int start = 0; - int minLen = s.length() + 1; - int subStr = 0; - for (int endWindow = 0; endWindow < s.length(); endWindow++) { - char right = s.charAt(endWindow); - if (map.containsKey(right)) { - map.put(right, map.get(right) - 1); - if (map.get(right) == 0) matched++; - } + int matched = 0; + int start = 0; + int minLen = s.length() + 1; + int subStr = 0; + for (int endWindow = 0; endWindow < s.length(); endWindow++) { + char right = s.charAt(endWindow); + if (map.containsKey(right)) { + map.put(right, map.get(right) - 1); + if (map.get(right) == 0) matched++; + } - while (matched == map.size()) { - if (minLen > endWindow - start + 1) { - minLen = endWindow - start + 1; - subStr = start; - } - char deleted = s.charAt(start++); - if (map.containsKey(deleted)) { - if (map.get(deleted) == 0) matched--; - map.put(deleted, map.get(deleted) + 1); - } - } + while (matched == map.size()) { + if (minLen > endWindow - start + 1) { + minLen = endWindow - start + 1; + subStr = start; + } + char deleted = s.charAt(start++); + if (map.containsKey(deleted)) { + if (map.get(deleted) == 0) matched--; + map.put(deleted, map.get(deleted) + 1); } - return minLen > s.length() ? "" : s.substring(subStr, subStr + minLen); + } } + return minLen > s.length() ? "" : s.substring(subStr, subStr + minLen); + } } diff --git a/java/763-Partition-Labels.java b/java/763-Partition-Labels.java index 6236a0b48..c19561683 100644 --- a/java/763-Partition-Labels.java +++ b/java/763-Partition-Labels.java @@ -1,23 +1,23 @@ class Solution { - public List partitionLabels(String s) { - List list = new ArrayList<>(); - HashMap map = new HashMap<>(); - for (int i = 0; i partitionLabels(String s) { + List list = new ArrayList<>(); + HashMap map = new HashMap<>(); + for (int i = 0; i < s.length(); i++) { + map.put(s.charAt(i), i); } + int j = 0; + int i = 0; + while (i < s.length()) { + int count = 0; + j = Math.max(j, map.get(s.charAt(i))); + while (i <= j) { + j = Math.max(j, map.get(s.charAt(i))); + i++; + count++; + } + list.add(count); + } + return list; + } } diff --git a/java/767-Reorganize-String.java b/java/767-Reorganize-String.java index 035560794..c64ab812b 100644 --- a/java/767-Reorganize-String.java +++ b/java/767-Reorganize-String.java @@ -1,40 +1,41 @@ //See this comment for explanation https://leetcode.com/problems/reorganize-string/discuss/113440/Java-solution-PriorityQueue/211009 class Solution { - public String reorganizeString(String s) { - HashMap map = new HashMap<>(); - for (int i = 0; i> pq = new PriorityQueue<>((a,b)->b.getValue()-a.getValue()); - pq.addAll(map.entrySet()); - - StringBuilder sb = new StringBuilder(); - - while (!pq.isEmpty()) { - Map.Entry temp1 = pq.poll(); - //if the character at sb's end is different from the max frequency character or the string is empty - if (sb.length()==0 || sb.charAt(sb.length()-1)!=temp1.getKey()) { - sb.append(temp1.getKey()); - //update the value - temp1.setValue(temp1.getValue()-1); - } else { //the character is same - //hold the current character and look for the 2nd most frequent character - Map.Entry temp2 = pq.poll(); - //if there is no temp2 i.e. the temp1 was the only character in the heap then there is no way to avoid adjacent duplicate values - if (temp2==null) - return ""; - //else do the same thing as above - sb.append(temp2.getKey()); - //update the value - temp2.setValue(temp2.getValue()-1); - //if still has some value left add again to the heap - if (temp2.getValue()!=0) - pq.offer(temp2); - } - if (temp1.getValue()!=0) - pq.offer(temp1); - } - return sb.toString(); + + public String reorganizeString(String s) { + HashMap map = new HashMap<>(); + for (int i = 0; i < s.length(); i++) { + map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1); + } + PriorityQueue> pq = new PriorityQueue<>( + (a, b) -> + b.getValue() - a.getValue() + ); + pq.addAll(map.entrySet()); + + StringBuilder sb = new StringBuilder(); + + while (!pq.isEmpty()) { + Map.Entry temp1 = pq.poll(); + //if the character at sb's end is different from the max frequency character or the string is empty + if (sb.length() == 0 || sb.charAt(sb.length() - 1) != temp1.getKey()) { + sb.append(temp1.getKey()); + //update the value + temp1.setValue(temp1.getValue() - 1); + } else { //the character is same + //hold the current character and look for the 2nd most frequent character + Map.Entry temp2 = pq.poll(); + //if there is no temp2 i.e. the temp1 was the only character in the heap then there is no way to avoid adjacent duplicate values + if (temp2 == null) return ""; + //else do the same thing as above + sb.append(temp2.getKey()); + //update the value + temp2.setValue(temp2.getValue() - 1); + //if still has some value left add again to the heap + if (temp2.getValue() != 0) pq.offer(temp2); + } + if (temp1.getValue() != 0) pq.offer(temp1); } + return sb.toString(); + } } diff --git a/java/779-K-th-Symbol-in-Grammar.java b/java/779-K-th-Symbol-in-Grammar.java index 5d6c21e9b..9a4cec623 100644 --- a/java/779-K-th-Symbol-in-Grammar.java +++ b/java/779-K-th-Symbol-in-Grammar.java @@ -2,15 +2,14 @@ //Asked in: Google (lintcode) class Solution { - public int kthGrammar(int n, int k) { - if (n==1 || k==1) return 0; - int prevK = (int)Math.pow(2, n-2); - if (k<=prevK) - return kthGrammar(n-1, k); - else { - int presK = k%prevK; - int val = kthGrammar(n-1, presK==0?k/2:k%prevK); - return val==1?0:1; - } + + public int kthGrammar(int n, int k) { + if (n == 1 || k == 1) return 0; + int prevK = (int) Math.pow(2, n - 2); + if (k <= prevK) return kthGrammar(n - 1, k); else { + int presK = k % prevK; + int val = kthGrammar(n - 1, presK == 0 ? k / 2 : k % prevK); + return val == 1 ? 0 : 1; } + } } diff --git a/java/78-Subsets.java b/java/78-Subsets.java index 9544342dd..f5de07d2e 100644 --- a/java/78-Subsets.java +++ b/java/78-Subsets.java @@ -1,23 +1,29 @@ //The idea is to have two conditions: One in which we will take the element into consideration, Second in which we won't take the element into consideration. //This video was good for code explanation. https://www.youtube.com/watch?v=6BPurabdAl4&t=508s&ab_channel=Fraz class Solution { - public List> subsets(int[] nums) { - List> ans = new ArrayList<>(); - List list = new ArrayList<>(); - helper(ans, 0, nums, list); - return ans; - } - - public void helper(List> ans, int start, int[] nums, List list) { - if (start>=nums.length) { - ans.add(new ArrayList<>(list)); //In java, we will have to add like this otherwise it'll give null as it'll just have the reference instead of actual values. - } else { - //add the element and start the recursive call - list.add(nums[start]); - helper(ans, start+1, nums, list); - //remove the element and do the backtracking call. - list.remove(list.size()-1); - helper(ans, start+1, nums, list); - } + + public List> subsets(int[] nums) { + List> ans = new ArrayList<>(); + List list = new ArrayList<>(); + helper(ans, 0, nums, list); + return ans; + } + + public void helper( + List> ans, + int start, + int[] nums, + List list + ) { + if (start >= nums.length) { + ans.add(new ArrayList<>(list)); //In java, we will have to add like this otherwise it'll give null as it'll just have the reference instead of actual values. + } else { + //add the element and start the recursive call + list.add(nums[start]); + helper(ans, start + 1, nums, list); + //remove the element and do the backtracking call. + list.remove(list.size() - 1); + helper(ans, start + 1, nums, list); } + } } diff --git a/java/79-Word-Search.java b/java/79-Word-Search.java index fbf4d3949..f3a14308e 100644 --- a/java/79-Word-Search.java +++ b/java/79-Word-Search.java @@ -1,35 +1,45 @@ //This is a typical backtracking problem similar to Number of Islands. -//In number of Isalnds, we sinked the islands. Here, we will do the same by adding changing the value of the char. +//In number of Isalnds, we sinked the islands. Here, we will do the same by adding changing the value of the char. //I added 100 because it will exceed the ascii limit for characters and will change it to some ascii value which is not an alphabet. class Solution { - public boolean exist(char[][] board, String word) { - int m = board.length; - int n = board[0].length; - for (int i = 0; i=word.length()) - return true; - if (i<0 || j<0 || i>=m || j>=n || board[i][j]!=word.charAt(cur)) - return false; - boolean exist = false; - if (board[i][j]==word.charAt(cur)) { - board[i][j] +=100; - exist = check(board, word, i+1, j, m, n, cur+1) || - check(board, word, i, j+1, m, n, cur+1) || - check(board, word, i-1, j, m, n, cur+1) || - check(board, word, i, j-1, m, n, cur+1); - board[i][j] -= 100; - } - return exist; + return false; + } + + public boolean check( + char[][] board, + String word, + int i, + int j, + int m, + int n, + int cur + ) { + if (cur >= word.length()) return true; + if ( + i < 0 || j < 0 || i >= m || j >= n || board[i][j] != word.charAt(cur) + ) return false; + boolean exist = false; + if (board[i][j] == word.charAt(cur)) { + board[i][j] += 100; + exist = + check(board, word, i + 1, j, m, n, cur + 1) || + check(board, word, i, j + 1, m, n, cur + 1) || + check(board, word, i - 1, j, m, n, cur + 1) || + check(board, word, i, j - 1, m, n, cur + 1); + board[i][j] -= 100; } + return exist; + } } diff --git a/java/797-All-Paths-From-Source-to-Target.java b/java/797-All-Paths-From-Source-to-Target.java index 8de6967c1..84d020b12 100644 --- a/java/797-All-Paths-From-Source-to-Target.java +++ b/java/797-All-Paths-From-Source-to-Target.java @@ -1,22 +1,27 @@ class Solution { - public List> allPathsSourceTarget(int[][] graph) { - List> ans = new ArrayList<>(); - List list = new ArrayList<>(); - list.add(0); - dfs(ans, graph, list, 0); - return ans; + + public List> allPathsSourceTarget(int[][] graph) { + List> ans = new ArrayList<>(); + List list = new ArrayList<>(); + list.add(0); + dfs(ans, graph, list, 0); + return ans; + } + + public void dfs( + List> ans, + int[][] graph, + List list, + int i + ) { + if (i == graph.length - 1) { + ans.add(new ArrayList(list)); + return; } - - public void dfs(List> ans, int[][] graph, List list, int i) - { - if (i==graph.length-1) { - ans.add(new ArrayList(list)); - return; - } - for (int val: graph[i]) { - list.add(val); - dfs(ans, graph, list, val); - list.remove(list.size()-1); - } + for (int val : graph[i]) { + list.add(val); + dfs(ans, graph, list, val); + list.remove(list.size() - 1); } + } } diff --git a/java/83. Remove Duplicates from Sorted List.java b/java/83. Remove Duplicates from Sorted List.java index e7362e299..d23e6bec6 100644 --- a/java/83. Remove Duplicates from Sorted List.java +++ b/java/83. Remove Duplicates from Sorted List.java @@ -1,20 +1,21 @@ //Three pointer approach that we use in in-place reversal of linked list. class Solution { - public ListNode deleteDuplicates(ListNode head) { - ListNode p = null; - ListNode q = null; - ListNode r = head; - while (r!=null) { - if (q!=null && q.val == r.val) { - r = r.next; - q.next = r; - }else { - p = q; - q = r; - r = r.next; - } - } - return head; + + public ListNode deleteDuplicates(ListNode head) { + ListNode p = null; + ListNode q = null; + ListNode r = head; + while (r != null) { + if (q != null && q.val == r.val) { + r = r.next; + q.next = r; + } else { + p = q; + q = r; + r = r.next; + } } + return head; + } } diff --git a/java/84-Largest-Rectangle-in-Histogram.java b/java/84-Largest-Rectangle-in-Histogram.java index a998ee345..937a61d68 100644 --- a/java/84-Largest-Rectangle-in-Histogram.java +++ b/java/84-Largest-Rectangle-in-Histogram.java @@ -1,39 +1,40 @@ class Solution { - public int largestRectangleArea(int[] heights) { - int n = heights.length; - int[] leftMin = new int[n]; - Stack left = new Stack<>(); - Arrays.fill(leftMin, -1); - for (int i = heights.length-1; i>=0; i--) { - if (left.isEmpty() || heights[i]>=heights[left.peek()]) { - left.add(i); - } else { - while (!left.isEmpty() && heights[left.peek()]>heights[i]) { - leftMin[left.peek()] = i; - left.pop(); - } - left.add(i); - } + + public int largestRectangleArea(int[] heights) { + int n = heights.length; + int[] leftMin = new int[n]; + Stack left = new Stack<>(); + Arrays.fill(leftMin, -1); + for (int i = heights.length - 1; i >= 0; i--) { + if (left.isEmpty() || heights[i] >= heights[left.peek()]) { + left.add(i); + } else { + while (!left.isEmpty() && heights[left.peek()] > heights[i]) { + leftMin[left.peek()] = i; + left.pop(); } - int[] rightMin = new int[n]; - Stack right = new Stack<>(); - Arrays.fill(rightMin, heights.length); - for (int i = 0; i=heights[right.peek()]) { - right.add(i); - } else { - while (!right.isEmpty() && heights[right.peek()]>heights[i]) { - rightMin[right.peek()] = i; - right.pop(); - } - right.add(i); - } - } - // System.out.println() - int area = Integer.MIN_VALUE; - for (int i = 0; i right = new Stack<>(); + Arrays.fill(rightMin, heights.length); + for (int i = 0; i < heights.length; i++) { + if (right.isEmpty() || heights[i] >= heights[right.peek()]) { + right.add(i); + } else { + while (!right.isEmpty() && heights[right.peek()] > heights[i]) { + rightMin[right.peek()] = i; + right.pop(); } - return area; + right.add(i); + } + } + // System.out.println() + int area = Integer.MIN_VALUE; + for (int i = 0; i < heights.length; i++) { + area = Math.max(area, heights[i] * (rightMin[i] - leftMin[i] - 1)); } + return area; + } } diff --git a/java/852. Peak Index in a Mountain Array.java b/java/852. Peak Index in a Mountain Array.java index 678b5ee6c..69772559d 100644 --- a/java/852. Peak Index in a Mountain Array.java +++ b/java/852. Peak Index in a Mountain Array.java @@ -1,18 +1,20 @@ //Use binary search class Solution { - public int peakIndexInMountainArray(int[] arr) { - int start = 0; - int end = arr.length; - int n = arr.length; - while (start<=end) { - int mid = start+(end-start)/2; - if (mid!=0 && mid!=n-1 && arr[mid-1]arr[mid]) - start = mid+1; - else if (mid!=0 && arr[mid-1]>arr[mid]) - end = mid-1; - } - return end; + + public int peakIndexInMountainArray(int[] arr) { + int start = 0; + int end = arr.length; + int n = arr.length; + while (start <= end) { + int mid = start + (end - start) / 2; + if ( + mid != 0 && + mid != n - 1 && + arr[mid - 1] < arr[mid] && + arr[mid + 1] < arr[mid] + ) return mid; else if (mid != n - 1 && arr[mid + 1] > arr[mid]) start = + mid + 1; else if (mid != 0 && arr[mid - 1] > arr[mid]) end = mid - 1; } + return end; + } } diff --git a/java/853-Car Fleet.java b/java/853-Car Fleet.java index 92fa67318..1070ee822 100644 --- a/java/853-Car Fleet.java +++ b/java/853-Car Fleet.java @@ -1,26 +1,23 @@ class Solution { - public int carFleet(int target, int[] position, int[] speed) { - if (position.length==1) - return 1; - Stack stack=new Stack<>(); - int[][] combine=new int[position.length][2]; - for(int i=0;io[0])); - for(int i=combine.length-1;i>=0;i--){ - double currentTime=(double)(target-combine[i][0])/combine[i][1]; - if(!stack.isEmpty() && currentTime<=stack.peek()){ - continue; - } - else{ - stack.push(currentTime); - } - } - return stack.size(); + + public int carFleet(int target, int[] position, int[] speed) { + if (position.length == 1) return 1; + Stack stack = new Stack<>(); + int[][] combine = new int[position.length][2]; + for (int i = 0; i < position.length; i++) { + combine[i][0] = position[i]; + combine[i][1] = speed[i]; } + + Arrays.sort(combine, java.util.Comparator.comparingInt(o -> o[0])); + for (int i = combine.length - 1; i >= 0; i--) { + double currentTime = (double) (target - combine[i][0]) / combine[i][1]; + if (!stack.isEmpty() && currentTime <= stack.peek()) { + continue; + } else { + stack.push(currentTime); + } + } + return stack.size(); + } } diff --git a/java/863-All-Nodes-Distance-K-in-Binary-Tree.java b/java/863-All-Nodes-Distance-K-in-Binary-Tree.java index 77fcecd68..42c19bf9c 100644 --- a/java/863-All-Nodes-Distance-K-in-Binary-Tree.java +++ b/java/863-All-Nodes-Distance-K-in-Binary-Tree.java @@ -1,51 +1,49 @@ //Just store the value for parent values of the nodes in a map and just do bfs as we do in graph. class Solution { - public List distanceK(TreeNode root, TreeNode target, int k) { - HashMap map = new HashMap<>(); - //First bfs to make a mapping to the parent nodes - Queue q1 = new LinkedList<>(); - q1.offer(root); - while (!q1.isEmpty()) { - int size = q1.size(); - for (int i = 0;i distanceK(TreeNode root, TreeNode target, int k) { + HashMap map = new HashMap<>(); + //First bfs to make a mapping to the parent nodes + Queue q1 = new LinkedList<>(); + q1.offer(root); + while (!q1.isEmpty()) { + int size = q1.size(); + for (int i = 0; i < size; i++) { + TreeNode cur = q1.poll(); + if (cur.left != null) { + q1.offer(cur.left); + map.put(cur.left, cur); + } + if (cur.right != null) { + q1.offer(cur.right); + map.put(cur.right, cur); } - //Now do the bfs - //Same as we do in graphs with a visited set - Queue q2 = new LinkedList<>(); - HashSet vis = new HashSet<>(); - List ans = new ArrayList<>(); - int dis = 0; - q2.offer(target); - while (!q2.isEmpty()) { - int size = q2.size(); - for (int i = 0; i q2 = new LinkedList<>(); + HashSet vis = new HashSet<>(); + List ans = new ArrayList<>(); + int dis = 0; + q2.offer(target); + while (!q2.isEmpty()) { + int size = q2.size(); + for (int i = 0; i < size; i++) { + TreeNode cur = q2.poll(); + if (!vis.contains(cur)) { + if (cur.left != null) q2.offer(cur.left); + if (cur.right != null) q2.offer(cur.right); + if (map.get(cur) != null) q2.offer(map.get(cur)); + if (dis == k) { + ans.add(cur.val); + } } - return ans; + vis.add(cur); + } + dis++; } + return ans; + } } diff --git a/java/875-Koko-Eating-Bananas.java b/java/875-Koko-Eating-Bananas.java index 4e187b609..a2f25089c 100644 --- a/java/875-Koko-Eating-Bananas.java +++ b/java/875-Koko-Eating-Bananas.java @@ -1,33 +1,34 @@ class Solution { - public int minEatingSpeed(int[] piles, int h) { - // Initalize the left and right boundaries - int left = 1, right = 1; - for (int pile : piles) { - right = Math.max(right, pile); - } - while (left < right) { - // Get the middle index between left and right boundary indexes. - // hourSpent stands for the total hour Koko spends. - int middle = (left + right) / 2; - int hourSpent = 0; + public int minEatingSpeed(int[] piles, int h) { + // Initalize the left and right boundaries + int left = 1, right = 1; + for (int pile : piles) { + right = Math.max(right, pile); + } - // Iterate over the piles and calculate hourSpent. - // We increase the hourSpent by ceil(pile / middle) - for (int pile : piles) { - hourSpent += Math.ceil((double) pile / middle); - } + while (left < right) { + // Get the middle index between left and right boundary indexes. + // hourSpent stands for the total hour Koko spends. + int middle = (left + right) / 2; + int hourSpent = 0; - // Check if middle is a workable speed, and cut the search space by half. - if (hourSpent <= h) { - right = middle; - } else { - left = middle + 1; - } - } + // Iterate over the piles and calculate hourSpent. + // We increase the hourSpent by ceil(pile / middle) + for (int pile : piles) { + hourSpent += Math.ceil((double) pile / middle); + } - // Once the left and right boundaries coincide, we find the target value, - // that is, the minimum workable eating speed. - return right; + // Check if middle is a workable speed, and cut the search space by half. + if (hourSpent <= h) { + right = middle; + } else { + left = middle + 1; + } } + + // Once the left and right boundaries coincide, we find the target value, + // that is, the minimum workable eating speed. + return right; + } } diff --git a/java/876. Middle of the Linked List.java b/java/876. Middle of the Linked List.java index ce5df8d58..e0afb7456 100644 --- a/java/876. Middle of the Linked List.java +++ b/java/876. Middle of the Linked List.java @@ -1,12 +1,13 @@ //fast and slow pointer class Solution { - public ListNode middleNode(ListNode head) { - ListNode slow = head; - ListNode fast = head; - while (fast!=null && fast.next!=null) { - fast = fast.next.next; - slow = slow.next; - } - return slow; + + public ListNode middleNode(ListNode head) { + ListNode slow = head; + ListNode fast = head; + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; } + return slow; + } } diff --git a/java/90-Subsets-II.java b/java/90-Subsets-II.java index 97c6b97a2..73685784a 100644 --- a/java/90-Subsets-II.java +++ b/java/90-Subsets-II.java @@ -1,26 +1,31 @@ //Similar to subsets 1. Here, we'll just take care of the duplicates. //This video was helpful https://www.youtube.com/watch?v=mcg4qKbAmmY&t=316s&ab_channel=Fraz class Solution { - public List> subsetsWithDup(int[] nums) { - Arrays.sort(nums); - List> ans = new ArrayList<>(); - ArrayList list = new ArrayList<>(); - helper(ans, 0, nums, list, false); - return ans; + + public List> subsetsWithDup(int[] nums) { + Arrays.sort(nums); + List> ans = new ArrayList<>(); + ArrayList list = new ArrayList<>(); + helper(ans, 0, nums, list, false); + return ans; + } + + public void helper( + List> ans, + int start, + int[] nums, + List list, + boolean ignored + ) { + if (start >= nums.length) { + ans.add(new ArrayList<>(list)); + } else { + helper(ans, start + 1, nums, list, true); + //if we've ignored the value earlier then we must ignore all the values after that too + if (start > 0 && nums[start - 1] == nums[start] && ignored) return; + list.add(nums[start]); + helper(ans, start + 1, nums, list, false); + list.remove(list.size() - 1); } - - public void helper(List> ans, int start, int[] nums, List list, boolean ignored) { - if (start>=nums.length) { - ans.add(new ArrayList<>(list)); - } else { - helper(ans, start+1, nums, list, true); - //if we've ignored the value earlier then we must ignore all the values after that too - if (start>0 && nums[start-1]==nums[start] && ignored) - return; - list.add(nums[start]); - helper(ans, start+1, nums, list, false); - list.remove(list.size()-1); - } - } - + } } diff --git a/java/97-Interleaving-String.java b/java/97-Interleaving-String.java index 997cedf42..dfac8f6af 100644 --- a/java/97-Interleaving-String.java +++ b/java/97-Interleaving-String.java @@ -1,25 +1,26 @@ -class Solution { +class Solution { - public boolean isInterleave(String s1, String s2, String s3) { - if (s1.length() + s2.length() != s3.length()) { - return false; - } - - boolean[][] dp = new boolean[s1.length() + 1][s2.length() + 1]; - dp[s1.length()][s2.length()] = true; - - for (int i = dp.length - 1; i >= 0; i--) - for (int j = dp[0].length - 1; j >= 0; j--) { - if (i < s1.length() && s1.charAt(i) == s3.charAt(i + j) && dp[i + 1][j]) { - dp[i][j] = true; - } - if (j < s2.length() && s2.charAt(j) == s3.charAt(i + j) && dp[i][j + 1]) { - dp[i][j] = true; - } + public boolean isInterleave(String s1, String s2, String s3) { + if (s1.length() + s2.length() != s3.length()) { + return false; + } - } + boolean[][] dp = new boolean[s1.length() + 1][s2.length() + 1]; + dp[s1.length()][s2.length()] = true; - return dp[0][0]; + for (int i = dp.length - 1; i >= 0; i--) for ( + int j = dp[0].length - 1; + j >= 0; + j-- + ) { + if (i < s1.length() && s1.charAt(i) == s3.charAt(i + j) && dp[i + 1][j]) { + dp[i][j] = true; + } + if (j < s2.length() && s2.charAt(j) == s3.charAt(i + j) && dp[i][j + 1]) { + dp[i][j] = true; + } } + return dp[0][0]; + } } diff --git a/java/973-K-Closest-Points-to-Origin.java b/java/973-K-Closest-Points-to-Origin.java index 39fc11f7a..ada0807a1 100644 --- a/java/973-K-Closest-Points-to-Origin.java +++ b/java/973-K-Closest-Points-to-Origin.java @@ -2,44 +2,56 @@ //Time complexity O(Nlogk) class Solution { - public int[][] kClosest(int[][] points, int k) { - HashMap map = new HashMap<>(); - PriorityQueue> pq = new PriorityQueue<>((a,b)->Double.compare(a.getValue(),b.getValue())); - for (int i = 0; i map = new HashMap<>(); + PriorityQueue> pq = new PriorityQueue<>((a, b) -> + Double.compare(a.getValue(), b.getValue()) + ); + for (int i = 0; i < points.length; i++) { + map.put( + points[i], + Math.pow((Math.pow(points[i][0], 2) + Math.pow(points[i][1], 2)), 0.5) + ); //We can also ignore this rooting as I did in the next solution + } + for (Map.Entry set : map.entrySet()) { + pq.add(set); + } + int[][] ans = new int[k][2]; + for (int i = 0; i < k; i++) { + int[] temp = pq.poll().getKey(); + ans[i][0] = temp[0]; + ans[i][1] = temp[1]; } + return ans; + } } //Since, we need to find the minimum, it doens't matter if we square root them. As the minimum will remain the same after square rooting also. //Ex: 4.8<4.9 -> root(4.8) map = new HashMap<>(); - PriorityQueue> pq = new PriorityQueue<>((a,b)->a.getValue()-b.getValue()); - for (int i = 0; i map = new HashMap<>(); + PriorityQueue> pq = new PriorityQueue<>((a, b) -> + a.getValue() - b.getValue() + ); + for (int i = 0; i < points.length; i++) { + map.put( + points[i], + (int) (Math.pow(points[i][0], 2) + Math.pow(points[i][1], 2)) + ); + } + for (Map.Entry set : map.entrySet()) { + pq.add(set); + } + int[][] ans = new int[k][2]; + for (int i = 0; i < k; i++) { + int[] temp = pq.poll().getKey(); + ans[i][0] = temp[0]; + ans[i][1] = temp[1]; } + return ans; + } } diff --git a/java/98-Validate-Binary-Search-Tree.java b/java/98-Validate-Binary-Search-Tree.java index ba296426a..d7765d834 100644 --- a/java/98-Validate-Binary-Search-Tree.java +++ b/java/98-Validate-Binary-Search-Tree.java @@ -14,20 +14,19 @@ * } */ class Solution { - public boolean isValidBST(TreeNode root) { - if (root == null) return true; - return dfs(root, null, null); - } - - private boolean dfs(TreeNode root, Integer min, Integer max) { - if (root == null) return true; - if ((min != null && root.val <= min) || max != null && root.val >= max) { - return false; - } + public boolean isValidBST(TreeNode root) { + if (root == null) return true; + return dfs(root, null, null); + } - return dfs(root.left, min, root.val) && dfs(root.right, root.val, max); + private boolean dfs(TreeNode root, Integer min, Integer max) { + if (root == null) return true; + if ((min != null && root.val <= min) || max != null && root.val >= max) { + return false; } -} + return dfs(root.left, min, root.val) && dfs(root.right, root.val, max); + } +} diff --git a/java/981-Time-Based-Key-Value-Store.java b/java/981-Time-Based-Key-Value-Store.java index 7d559a28f..cf5c9e44c 100644 --- a/java/981-Time-Based-Key-Value-Store.java +++ b/java/981-Time-Based-Key-Value-Store.java @@ -1,30 +1,32 @@ class TimeMap { - HashMap>> map; + HashMap>> map; - public TimeMap() { - map = new HashMap<>(); - } - - public void set(String key, String value, int timestamp) { - if (!map.containsKey(key)) map.put(key, new ArrayList<>()); - map.get(key).add(new Pair(value, timestamp)); - } - - public String get(String key, int timestamp) { - if (!map.containsKey(key)) return ""; - List> list = map.get(key); - return search(list, timestamp); - } - - public String search(List> list, int timestamp) { - int start = 0; - int end = list.size()-1; - while (start(); + } + + public void set(String key, String value, int timestamp) { + if (!map.containsKey(key)) map.put(key, new ArrayList<>()); + map.get(key).add(new Pair(value, timestamp)); + } + + public String get(String key, int timestamp) { + if (!map.containsKey(key)) return ""; + List> list = map.get(key); + return search(list, timestamp); + } + + public String search(List> list, int timestamp) { + int start = 0; + int end = list.size() - 1; + while (start < end) { + int mid = start + (end - start + 1) / 2; + if (list.get(mid).getValue() <= timestamp) start = mid; else end = + mid - 1; } + return list.get(start).getValue() <= timestamp + ? list.get(start).getKey() + : ""; + } } diff --git a/java/986-Interval-List-Intersections.java b/java/986-Interval-List-Intersections.java index 7225191b5..645bde4ad 100644 --- a/java/986-Interval-List-Intersections.java +++ b/java/986-Interval-List-Intersections.java @@ -2,6 +2,7 @@ //Just two pointer approach class Solution { + public int[][] intervalIntersection(int[][] A, int[][] B) { List ans = new ArrayList(); int i = 0, j = 0; @@ -12,14 +13,10 @@ public int[][] intervalIntersection(int[][] A, int[][] B) { // hi - the endpoint of the intersection int lo = Math.max(A[i][0], B[j][0]); int hi = Math.min(A[i][1], B[j][1]); - if (lo <= hi) - ans.add(new int[]{lo, hi}); + if (lo <= hi) ans.add(new int[] { lo, hi }); // Remove the interval with the smallest endpoint - if (A[i][1] < B[j][1]) - i++; - else - j++; + if (A[i][1] < B[j][1]) i++; else j++; } return ans.toArray(new int[ans.size()][]); diff --git a/java/994-Rotting-Oranges.java b/java/994-Rotting-Oranges.java index 1de126c9a..39a778b2c 100644 --- a/java/994-Rotting-Oranges.java +++ b/java/994-Rotting-Oranges.java @@ -1,34 +1,36 @@ class Solution { - public int orangesRotting(int[][] grid) { - int m = grid.length, n = grid[0].length; - Queue queue = new LinkedList<>(); - int fresh = 0; - - for(int i = 0 ; i < m ; i += 1) { - for(int j = 0 ; j < n ; j += 1) { - if(grid[i][j] == 2) queue.offer(new int[]{i , j}); - else if(grid[i][j] == 1) fresh += 1; - } - } - - int count = 0; - int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}}; - while(!queue.isEmpty() && fresh != 0) { - count += 1; - int sz = queue.size(); - for(int i = 0 ; i < sz ; i += 1) { - int[] rotten = queue.poll(); - int r = rotten[0], c = rotten[1]; - for(int[] dir : dirs) { - int x = r + dir[0], y = c + dir[1]; - if (0<=x && x queue = new LinkedList<>(); + int fresh = 0; + + for (int i = 0; i < m; i += 1) { + for (int j = 0; j < n; j += 1) { + if (grid[i][j] == 2) queue.offer(new int[] { i, j }); else if ( + grid[i][j] == 1 + ) fresh += 1; + } + } + + int count = 0; + int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } }; + while (!queue.isEmpty() && fresh != 0) { + count += 1; + int sz = queue.size(); + for (int i = 0; i < sz; i += 1) { + int[] rotten = queue.poll(); + int r = rotten[0], c = rotten[1]; + for (int[] dir : dirs) { + int x = r + dir[0], y = c + dir[1]; + if (0 <= x && x < m && 0 <= y && y < n && grid[x][y] == 1) { + grid[x][y] = 2; + queue.offer(new int[] { x, y }); + fresh -= 1; + } } - return fresh == 0 ? count : -1; + } } -} \ No newline at end of file + return fresh == 0 ? count : -1; + } +} diff --git a/javascript/1-Two-Sum.js b/javascript/1-Two-Sum.js index 56e9b10fe..a40f78506 100644 --- a/javascript/1-Two-Sum.js +++ b/javascript/1-Two-Sum.js @@ -3,13 +3,13 @@ * @param {number} target * @return {number[]} */ -var twoSum = function(nums, target) { - let map = {}; - for (let i = 0; i < nums.length; i++) { - if (target - nums[i] in map) { - return [map[target-nums[i]], i]; - } else { - map[nums[i]] = i; - } +var twoSum = function (nums, target) { + let map = {}; + for (let i = 0; i < nums.length; i++) { + if (target - nums[i] in map) { + return [map[target - nums[i]], i]; + } else { + map[nums[i]] = i; } + } }; diff --git a/javascript/100-Same-Tree.js b/javascript/100-Same-Tree.js index 25db45766..e129eeb95 100644 --- a/javascript/100-Same-Tree.js +++ b/javascript/100-Same-Tree.js @@ -11,8 +11,8 @@ * @param {TreeNode} q * @return {boolean} */ -var isSameTree = function(p, q) { - if (!p && !q) return true; - if (!p || !q || p.val !== q.val) return false; - return isSameTree(p.right,q.right) && isSameTree(p.left, q.left); +var isSameTree = function (p, q) { + if (!p && !q) return true; + if (!p || !q || p.val !== q.val) return false; + return isSameTree(p.right, q.right) && isSameTree(p.left, q.left); }; diff --git a/javascript/102-Binary-Tree-Level-Order-Traversal.js b/javascript/102-Binary-Tree-Level-Order-Traversal.js index 9318404c7..cb8dabd72 100644 --- a/javascript/102-Binary-Tree-Level-Order-Traversal.js +++ b/javascript/102-Binary-Tree-Level-Order-Traversal.js @@ -10,24 +10,23 @@ * @param {TreeNode} root * @return {number[][]} */ -var levelOrder = function(root) { - - if(!root) return []; +var levelOrder = function (root) { + if (!root) return []; - const result = []; - const queue = [root]; - - while(queue.length){ - const numNodes = queue.length; - const temp = []; - for(let i = 0; i < numNodes; i++){ - const subtree = queue.shift(); - temp.push(subtree.val) - if(subtree.left !== null) queue.push(subtree.left); - if(subtree.right !== null) queue.push(subtree.right); - } - result.push(temp) + const result = []; + const queue = [root]; + + while (queue.length) { + const numNodes = queue.length; + const temp = []; + for (let i = 0; i < numNodes; i++) { + const subtree = queue.shift(); + temp.push(subtree.val); + if (subtree.left !== null) queue.push(subtree.left); + if (subtree.right !== null) queue.push(subtree.right); } - - return result; + result.push(temp); + } + + return result; }; diff --git a/javascript/104-Maximum-Depth-of-Binary-Tree.js b/javascript/104-Maximum-Depth-of-Binary-Tree.js index 7cf81388a..ab6008f57 100644 --- a/javascript/104-Maximum-Depth-of-Binary-Tree.js +++ b/javascript/104-Maximum-Depth-of-Binary-Tree.js @@ -11,13 +11,13 @@ * @return {number} */ var maxDepth = (root) => { - let maxDepth = 0; - let DFS = (node, depth) => { - if (!node) return maxDepth; - if (depth > maxDepth) maxDepth = depth; - DFS(node.right, depth + 1); - DFS(node.left, depth + 1); - } - DFS(root, 1); - return maxDepth; + let maxDepth = 0; + let DFS = (node, depth) => { + if (!node) return maxDepth; + if (depth > maxDepth) maxDepth = depth; + DFS(node.right, depth + 1); + DFS(node.left, depth + 1); + }; + DFS(root, 1); + return maxDepth; }; diff --git a/javascript/1046-Last-Stone-Weight.js b/javascript/1046-Last-Stone-Weight.js index 0669851be..5c8e3ff69 100644 --- a/javascript/1046-Last-Stone-Weight.js +++ b/javascript/1046-Last-Stone-Weight.js @@ -1,72 +1,73 @@ class Heap { - constructor(stones){ - this.heap = stones - this.size = stones.length - this.heapify(0) - } - right(pos) { - return 2*pos + 2 - } - left(pos) { - return 2*pos + 1 - } - isleaf(pos) { - if (2*pos + 1 >= this.size) return true - return false - } - swap(a,b){ - let temp = this.heap[a] - this.heap[a] = this.heap[b] - this.heap[b] = temp - } - fix(pos){ - if (this.isleaf(pos)) return - let left = this.left(pos) - let right = this.right(pos) - let bigger = left - if (right < this.size) bigger = this.heap[left] > this.heap[right] ? left : right - if (this.heap[pos] < this.heap[bigger]) { - this.swap(pos,bigger) - this.fix(bigger) - } - } - heapify(pos){ - if (this.isleaf(pos)) return - this.heapify(this.left(pos)) - this.heapify(this.right(pos)) - this.fix(pos) - } - delete(){ - this.swap(0, --this.size) - this.fix(0) - return this.heap[0] - } - insert(val){ - this.size++ - this.heap[this.size-1] = val - this.heapify(0) - } - peek(){ - return this.heap[0] + constructor(stones) { + this.heap = stones; + this.size = stones.length; + this.heapify(0); + } + right(pos) { + return 2 * pos + 2; + } + left(pos) { + return 2 * pos + 1; + } + isleaf(pos) { + if (2 * pos + 1 >= this.size) return true; + return false; + } + swap(a, b) { + let temp = this.heap[a]; + this.heap[a] = this.heap[b]; + this.heap[b] = temp; + } + fix(pos) { + if (this.isleaf(pos)) return; + let left = this.left(pos); + let right = this.right(pos); + let bigger = left; + if (right < this.size) + bigger = this.heap[left] > this.heap[right] ? left : right; + if (this.heap[pos] < this.heap[bigger]) { + this.swap(pos, bigger); + this.fix(bigger); } + } + heapify(pos) { + if (this.isleaf(pos)) return; + this.heapify(this.left(pos)); + this.heapify(this.right(pos)); + this.fix(pos); + } + delete() { + this.swap(0, --this.size); + this.fix(0); + return this.heap[0]; + } + insert(val) { + this.size++; + this.heap[this.size - 1] = val; + this.heapify(0); + } + peek() { + return this.heap[0]; + } } /** * @param {number[]} stones * @return {number} */ -var lastStoneWeight = function(stones) { - //use a max heap to pop off the top 2 stones at each time - //if result is 0 we can do nothing - //if the result is a new weight we can push it back to the heap - const heap = new Heap(stones) - while(heap.size > 1) { - let x = heap.peek() - heap.delete() - let y = heap.peek() - heap.delete() - const res = x-y - if (res > 0) heap.insert(res) - } - if (heap.size) return heap.peek() - return 0 +var lastStoneWeight = function (stones) { + //use a max heap to pop off the top 2 stones at each time + //if result is 0 we can do nothing + //if the result is a new weight we can push it back to the heap + const heap = new Heap(stones); + while (heap.size > 1) { + let x = heap.peek(); + heap.delete(); + let y = heap.peek(); + heap.delete(); + const res = x - y; + if (res > 0) heap.insert(res); + } + if (heap.size) return heap.peek(); + return 0; }; diff --git a/javascript/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.js b/javascript/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.js index 84cbad6e8..39865660f 100644 --- a/javascript/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.js +++ b/javascript/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.js @@ -1,10 +1,10 @@ -function buildTree(preorder, inorder) { - if (!preorder.length || !inorder.length) return null; - - let root = new TreeNode(preorder[0]); - let mid = inorder.indexOf(preorder[0]); - - root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid)); - root.right = buildTree(preorder.slice(mid + 1), inorder.slice(mid + 1)); - return root; -} +function buildTree(preorder, inorder) { + if (!preorder.length || !inorder.length) return null; + + let root = new TreeNode(preorder[0]); + let mid = inorder.indexOf(preorder[0]); + + root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid)); + root.right = buildTree(preorder.slice(mid + 1), inorder.slice(mid + 1)); + return root; +} diff --git a/javascript/11-Container-With-Most-Water.js b/javascript/11-Container-With-Most-Water.js index e03b11da0..99c9fd507 100644 --- a/javascript/11-Container-With-Most-Water.js +++ b/javascript/11-Container-With-Most-Water.js @@ -2,19 +2,19 @@ * @param {number[]} height * @return {number} */ -var maxArea = function(height) { - let max = 0; - let i = 0; - let j = height.length - 1; - - while (i < j) { - const curr = (j - i) * Math.min(height[i], height[j]); - max = Math.max(curr, max); - if (height[i] > height[j]) { - j--; - } else { - i++; - } +var maxArea = function (height) { + let max = 0; + let i = 0; + let j = height.length - 1; + + while (i < j) { + const curr = (j - i) * Math.min(height[i], height[j]); + max = Math.max(curr, max); + if (height[i] > height[j]) { + j--; + } else { + i++; } - return max; + } + return max; }; diff --git a/javascript/110-Balanced-Binary-Tree.js b/javascript/110-Balanced-Binary-Tree.js index ba9665fe7..0e7058857 100644 --- a/javascript/110-Balanced-Binary-Tree.js +++ b/javascript/110-Balanced-Binary-Tree.js @@ -11,18 +11,19 @@ * @return {boolean} */ var isBalanced = function (root) { - const getHeight = (root) => { - if (!root) return [-1, true]; + const getHeight = (root) => { + if (!root) return [-1, true]; - const [leftHeight, leftBalanced] = getHeight(root.left); - const [rightHeight, rightBalanced] = getHeight(root.right); + const [leftHeight, leftBalanced] = getHeight(root.left); + const [rightHeight, rightBalanced] = getHeight(root.right); - const balanced = leftBalanced && rightBalanced && Math.abs(leftHeight - rightHeight) < 2; + const balanced = + leftBalanced && rightBalanced && Math.abs(leftHeight - rightHeight) < 2; - return [1 + Math.max(leftHeight, rightHeight), balanced]; - }; + return [1 + Math.max(leftHeight, rightHeight), balanced]; + }; - const balanced = getHeight(root)[1] - - return balanced; -}; \ No newline at end of file + const balanced = getHeight(root)[1]; + + return balanced; +}; diff --git a/javascript/1143-Longest-Common-Subsequence.js b/javascript/1143-Longest-Common-Subsequence.js index 04bd19884..0a417ef46 100644 --- a/javascript/1143-Longest-Common-Subsequence.js +++ b/javascript/1143-Longest-Common-Subsequence.js @@ -1,7 +1,7 @@ var longestCommonSubsequence = function (text1, text2) { let m = text1.length, n = text2.length, - DP = new Array(m + 1).fill(0).map(_ => new Array(n + 1).fill(0)); + DP = new Array(m + 1).fill(0).map((_) => new Array(n + 1).fill(0)); for (let x = m - 1; x >= 0; x--) for (let y = n - 1; y >= 0; y--) { diff --git a/javascript/115-Distinct-Subsequences.js b/javascript/115-Distinct-Subsequences.js index e0c334238..bdbfda31e 100644 --- a/javascript/115-Distinct-Subsequences.js +++ b/javascript/115-Distinct-Subsequences.js @@ -10,28 +10,27 @@ * @return {number} */ function numDistinct(s, t) { - - const sLen = s.length; - const tLen = t.length; - - if (sLen < tLen) { - return 0; - } - - const cache = new Array(tLen).fill(0); - - for (let r = sLen - 1; r >= 0; --r) { - let prev = 1; - for (let c = tLen - 1; c >= 0; --c) { - const curr = cache[c]; - if (s[r] === t[c]) { - cache[c] += prev; - } - prev = curr; - } + const sLen = s.length; + const tLen = t.length; + + if (sLen < tLen) { + return 0; + } + + const cache = new Array(tLen).fill(0); + + for (let r = sLen - 1; r >= 0; --r) { + let prev = 1; + for (let c = tLen - 1; c >= 0; --c) { + const curr = cache[c]; + if (s[r] === t[c]) { + cache[c] += prev; + } + prev = curr; } - - return cache[0]; + } + + return cache[0]; } ////////////////////////////////////////////////////////////////////////////// @@ -46,33 +45,27 @@ function numDistinct(s, t) { * @return {number} */ function numDistinct(s, t) { - - const sLen = s.length; - const tLen = t.length; - - if (sLen < tLen) { - return 0; - } - - const cache = new Array(sLen + 1).fill() - .map(() => new Array(tLen + 1)); - - cache[sLen].fill(0); - for (let r = 0; r <= sLen; ++r) { - cache[r][tLen] = 1; - } - - for (let r = sLen - 1; r >= 0; --r) { - for (let c = tLen - 1; c >= 0; --c) { - cache[r][c] = cache[r + 1][c] + ( - s[r] === t[c] - ? cache[r + 1][c + 1] - : 0 - ); - } + const sLen = s.length; + const tLen = t.length; + + if (sLen < tLen) { + return 0; + } + + const cache = new Array(sLen + 1).fill().map(() => new Array(tLen + 1)); + + cache[sLen].fill(0); + for (let r = 0; r <= sLen; ++r) { + cache[r][tLen] = 1; + } + + for (let r = sLen - 1; r >= 0; --r) { + for (let c = tLen - 1; c >= 0; --c) { + cache[r][c] = cache[r + 1][c] + (s[r] === t[c] ? cache[r + 1][c + 1] : 0); } - - return cache[0][0]; + } + + return cache[0][0]; } ////////////////////////////////////////////////////////////////////////////// @@ -87,35 +80,31 @@ function numDistinct(s, t) { * @return {number} */ function numDistinct(s, t) { - - const sLen = s.length; - const tLen = t.length; - - if (sLen < tLen) { - return 0; - } - - const cache = new Array(sLen).fill() - .map(() => new Array(tLen)); - - return countDistincts(); - - /** - * @param {number=} i = `0` - * @param {number=} j = `0` - * @return {number} - */ - function countDistincts(i = 0, j = 0) { - return j === tLen - ? 1 - : i === sLen - ? 0 - : cache[i][j] !== undefined - ? cache[i][j] - : cache[i][j] = countDistincts(i + 1, j) + ( - s[i] === t[j] - ? countDistincts(i + 1, j + 1) - : 0 - ); - } + const sLen = s.length; + const tLen = t.length; + + if (sLen < tLen) { + return 0; + } + + const cache = new Array(sLen).fill().map(() => new Array(tLen)); + + return countDistincts(); + + /** + * @param {number=} i = `0` + * @param {number=} j = `0` + * @return {number} + */ + function countDistincts(i = 0, j = 0) { + return j === tLen + ? 1 + : i === sLen + ? 0 + : cache[i][j] !== undefined + ? cache[i][j] + : (cache[i][j] = + countDistincts(i + 1, j) + + (s[i] === t[j] ? countDistincts(i + 1, j + 1) : 0)); + } } diff --git a/javascript/121-Best-Time-to-Buy-and-Sell-Stock.js b/javascript/121-Best-Time-to-Buy-and-Sell-Stock.js index c8436d470..a42e3331b 100644 --- a/javascript/121-Best-Time-to-Buy-and-Sell-Stock.js +++ b/javascript/121-Best-Time-to-Buy-and-Sell-Stock.js @@ -2,15 +2,15 @@ * @param {number[]} prices * @return {number} */ -var maxProfit = function(prices) { - let buy = prices[0]; - let profit = 0; - for (let i = 0; i < prices.length; i++) { - if (prices[i] < buy) { - buy = prices[i]; - } else { - profit = Math.max(prices[i] - buy, profit); - } +var maxProfit = function (prices) { + let buy = prices[0]; + let profit = 0; + for (let i = 0; i < prices.length; i++) { + if (prices[i] < buy) { + buy = prices[i]; + } else { + profit = Math.max(prices[i] - buy, profit); } - return profit; + } + return profit; }; diff --git a/javascript/124-Binary-Tree-Maximum-Path-Sum.js b/javascript/124-Binary-Tree-Maximum-Path-Sum.js index f5b4a526d..284ac6755 100644 --- a/javascript/124-Binary-Tree-Maximum-Path-Sum.js +++ b/javascript/124-Binary-Tree-Maximum-Path-Sum.js @@ -1,35 +1,35 @@ -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number} - */ -var maxPathSum = function(root) { - const res = [root.val]; - - // return max path sum without split - function dfs(root) { - if (!root) { - return 0; - } - - let leftMax = dfs(root.left); - let rightMax = dfs(root.right); - leftMax = Math.max(leftMax, 0); - rightMax = Math.max(rightMax, 0); - - // compute max path sum WITH split - res[0] = Math.max(res[0], root.val + leftMax + rightMax); - - return root.val + Math.max(leftMax, rightMax); - } - - dfs(root); - return res[0]; -}; \ No newline at end of file +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var maxPathSum = function (root) { + const res = [root.val]; + + // return max path sum without split + function dfs(root) { + if (!root) { + return 0; + } + + let leftMax = dfs(root.left); + let rightMax = dfs(root.right); + leftMax = Math.max(leftMax, 0); + rightMax = Math.max(rightMax, 0); + + // compute max path sum WITH split + res[0] = Math.max(res[0], root.val + leftMax + rightMax); + + return root.val + Math.max(leftMax, rightMax); + } + + dfs(root); + return res[0]; +}; diff --git a/javascript/125-Valid-Palindrome.js b/javascript/125-Valid-Palindrome.js index 243a4b614..ee2094687 100644 --- a/javascript/125-Valid-Palindrome.js +++ b/javascript/125-Valid-Palindrome.js @@ -1,25 +1,24 @@ const ALPHA_NUM = /^[a-zA-Z0-9]$/; function isPalindrome(s) { + let l = 0; + let r = s.length - 1; - let l = 0; - let r = s.length - 1; - - while(l < r){ - while(l < r && !ALPHA_NUM.test(s[l])){ - l++; - } - while(l < r && !ALPHA_NUM.test(s[r])){ - r--; - } - - if(s[l].toLowerCase() !== s[r].toLowerCase()) { - return false; - } + while (l < r) { + while (l < r && !ALPHA_NUM.test(s[l])) { + l++; + } + while (l < r && !ALPHA_NUM.test(s[r])) { + r--; + } - l++; - r--; + if (s[l].toLowerCase() !== s[r].toLowerCase()) { + return false; } - return true; + l++; + r--; + } + + return true; } diff --git a/javascript/127-Word-Ladder.js b/javascript/127-Word-Ladder.js index 364bba736..1228fcd38 100644 --- a/javascript/127-Word-Ladder.js +++ b/javascript/127-Word-Ladder.js @@ -5,7 +5,7 @@ var ladderLength = function (beginWord, endWord, wordList) { for (let word of wordList) { for (let x = 0; x < word.length; x++) { - const pattern = word.slice(0, x) + "*" + word.slice(x + 1); + const pattern = word.slice(0, x) + '*' + word.slice(x + 1); patternMap[pattern] = patternMap[pattern] || []; patternMap[pattern].push(word); } @@ -20,7 +20,7 @@ var ladderLength = function (beginWord, endWord, wordList) { const word = queue.shift(); if (word === endWord) return wordCount; for (let x = 0; x < word.length; x++) { - const pattern = word.slice(0, x) + "*" + word.slice(x + 1); + const pattern = word.slice(0, x) + '*' + word.slice(x + 1); for (let nei of patternMap[pattern]) { if (nei in visited) continue; visited[nei] = true; diff --git a/javascript/128-Longest-consecutive-sequence.js b/javascript/128-Longest-consecutive-sequence.js index c652043d1..10c47ad1d 100644 --- a/javascript/128-Longest-consecutive-sequence.js +++ b/javascript/128-Longest-consecutive-sequence.js @@ -11,42 +11,40 @@ * @return {number} */ function longestConsecutive(nums) { - - if (!nums.length) { - return 0; - } - - const map = Object.create(null); - let max = 0; - - for (const num of nums) { - - if (num in map) { - continue; - } - - const prev = num - 1; - const next = num + 1; - let len = 1; - - if (prev in map) { - if (next in map) { - len += map[prev] + map[next]; - map[prev - map[prev] + 1] = len; - map[next + map[next] - 1] = len; - } else { - len += map[prev]; - ++map[prev - map[prev] + 1]; - } - } else if (next in map) { - len += map[next]; - ++map[next + map[next] - 1]; - } - map[num] = len; - max = Math.max(max, len); - } - - return max; + if (!nums.length) { + return 0; + } + + const map = Object.create(null); + let max = 0; + + for (const num of nums) { + if (num in map) { + continue; + } + + const prev = num - 1; + const next = num + 1; + let len = 1; + + if (prev in map) { + if (next in map) { + len += map[prev] + map[next]; + map[prev - map[prev] + 1] = len; + map[next + map[next] - 1] = len; + } else { + len += map[prev]; + ++map[prev - map[prev] + 1]; + } + } else if (next in map) { + len += map[next]; + ++map[next + map[next] - 1]; + } + map[num] = len; + max = Math.max(max, len); + } + + return max; } ////////////////////////////////////////////////////////////////////////////// @@ -65,26 +63,25 @@ function longestConsecutive(nums) { * @return {number} */ function longestConsecutive(nums) { + const set = new Set(nums); + let max = 0; - const set = new Set(nums); - let max = 0; - - for (let i = 0; i < nums.length; i++) { - const num = nums[i]; + for (let i = 0; i < nums.length; i++) { + const num = nums[i]; - if (set.has(num - 1)) { - continue; - } + if (set.has(num - 1)) { + continue; + } - let currentMax = 1; - while (set.has(num + currentMax)) { - currentMax++; - } + let currentMax = 1; + while (set.has(num + currentMax)) { + currentMax++; + } - if (currentMax > max) { - max = currentMax; - } + if (currentMax > max) { + max = currentMax; } + } - return max; + return max; } diff --git a/javascript/13-Roman-to-Integer.js b/javascript/13-Roman-to-Integer.js index 993d6738b..a16bc3ee2 100644 --- a/javascript/13-Roman-to-Integer.js +++ b/javascript/13-Roman-to-Integer.js @@ -3,62 +3,62 @@ * @return {number} */ var romanToInt = function (s) { - let romans = { - I: 1, - V: 5, - X: 10, - L: 50, - C: 100, - D: 500, - M: 1000, - }; + let romans = { + I: 1, + V: 5, + X: 10, + L: 50, + C: 100, + D: 500, + M: 1000, + }; - let arr = s.split(""); + let arr = s.split(''); - let sum = 0; + let sum = 0; - for (let i = arr.length - 1; i >= 0; i--) { - // IV : 4 - if (romans[arr[i]] === romans["V"]) { - if (romans[arr[i - 1]] === romans["I"]) { - sum -= 1 * 2; - } - } - // IX : 4 - if (romans[arr[i]] === romans["X"]) { - if (romans[arr[i - 1]] === romans["I"]) { - sum -= 1 * 2; - } - } - // XL : 40 - if (romans[arr[i]] === romans["L"]) { - if (romans[arr[i - 1]] === romans["X"]) { - sum -= 10 * 2; - } - } - // XC : 90 - if (romans[arr[i]] === romans["C"]) { - if (romans[arr[i - 1]] === romans["X"]) { - sum -= 10 * 2; - } - } - // CD : 400 - if (romans[arr[i]] === romans["D"]) { - if (romans[arr[i - 1]] === romans["C"]) { - sum -= 100 * 2; - } - } - // CM : 900 - if (romans[arr[i]] === romans["M"]) { - if (romans[arr[i - 1]] === romans["C"]) { - sum -= 100 * 2; - } - } - - sum += romans[arr[i]]; + for (let i = arr.length - 1; i >= 0; i--) { + // IV : 4 + if (romans[arr[i]] === romans['V']) { + if (romans[arr[i - 1]] === romans['I']) { + sum -= 1 * 2; + } + } + // IX : 4 + if (romans[arr[i]] === romans['X']) { + if (romans[arr[i - 1]] === romans['I']) { + sum -= 1 * 2; + } + } + // XL : 40 + if (romans[arr[i]] === romans['L']) { + if (romans[arr[i - 1]] === romans['X']) { + sum -= 10 * 2; + } + } + // XC : 90 + if (romans[arr[i]] === romans['C']) { + if (romans[arr[i - 1]] === romans['X']) { + sum -= 10 * 2; + } } + // CD : 400 + if (romans[arr[i]] === romans['D']) { + if (romans[arr[i - 1]] === romans['C']) { + sum -= 100 * 2; + } + } + // CM : 900 + if (romans[arr[i]] === romans['M']) { + if (romans[arr[i - 1]] === romans['C']) { + sum -= 100 * 2; + } + } + + sum += romans[arr[i]]; + } - return sum; + return sum; }; // Runtime: 148 ms, faster than 80.16% of JavaScript online submissions for Roman to Integer. diff --git a/javascript/130-Surrounded-Regions.js b/javascript/130-Surrounded-Regions.js index cf44f595d..07af00cf3 100644 --- a/javascript/130-Surrounded-Regions.js +++ b/javascript/130-Surrounded-Regions.js @@ -12,59 +12,57 @@ * @return {void} Do not return anything, modify board in-place instead. */ function solve(board) { - - const rowLen = board.length; - const colLen = board[0].length; - const lastRow = rowLen - 1; - const lastCol = colLen - 1; - - for (let r = 0; r < rowLen; ++r) { - markSeen(r, 0); - markSeen(r, lastCol); - } - for (let c = 1; c < lastCol; ++c) { - markSeen(0, c); - markSeen(lastRow, c); - } - - for (let r = 0; r < rowLen; ++r) { - for (let c = 0; c < colLen; ++c) { - switch (board[r][c]) { - case 'O': - board[r][c] = 'X'; - break; - case 'A': - board[r][c] = 'O'; - break; - } - } - } - - /** - * @param {number} r - * @param {number} c - * @return {void} - */ - function markSeen(r, c) { - - if (!inBounds(r, c) || board[r][c] !== 'O') { - return; - } - - board[r][c] = 'A'; - - markSeen(r - 1, c); - markSeen(r + 1, c); - markSeen(r, c - 1); - markSeen(r, c + 1); + const rowLen = board.length; + const colLen = board[0].length; + const lastRow = rowLen - 1; + const lastCol = colLen - 1; + + for (let r = 0; r < rowLen; ++r) { + markSeen(r, 0); + markSeen(r, lastCol); + } + for (let c = 1; c < lastCol; ++c) { + markSeen(0, c); + markSeen(lastRow, c); + } + + for (let r = 0; r < rowLen; ++r) { + for (let c = 0; c < colLen; ++c) { + switch (board[r][c]) { + case 'O': + board[r][c] = 'X'; + break; + case 'A': + board[r][c] = 'O'; + break; + } } - - /** - * @param {number} r - * @param {number} c - * @return {boolean} - */ - function inBounds(r, c) { - return r >= 0 && c >= 0 && r < rowLen && c < colLen; + } + + /** + * @param {number} r + * @param {number} c + * @return {void} + */ + function markSeen(r, c) { + if (!inBounds(r, c) || board[r][c] !== 'O') { + return; } + + board[r][c] = 'A'; + + markSeen(r - 1, c); + markSeen(r + 1, c); + markSeen(r, c - 1); + markSeen(r, c + 1); + } + + /** + * @param {number} r + * @param {number} c + * @return {boolean} + */ + function inBounds(r, c) { + return r >= 0 && c >= 0 && r < rowLen && c < colLen; + } } diff --git a/javascript/131-Palindrome-Partitioning.js b/javascript/131-Palindrome-Partitioning.js index 5cb02124a..514eec049 100644 --- a/javascript/131-Palindrome-Partitioning.js +++ b/javascript/131-Palindrome-Partitioning.js @@ -1,33 +1,33 @@ -function partition(s) { - let res = []; - let part = []; - - function dfs(i) { - if (i >= s.length) { - res.push(part.slice()); - return; - } - - for (let j = i; j < s.length; j++) { - if (isPali(s, i, j)) { - part.push(s.slice(i, j + 1)); - dfs(j + 1); - part.pop(); - } - } - } - - dfs(0); - return res; - - function isPali(s, l, r) { - while (l < r) { - if (s[l] != s[r]) { - return false; - } - l = l + 1; - r = r - 1; - } - return true; - } -} +function partition(s) { + let res = []; + let part = []; + + function dfs(i) { + if (i >= s.length) { + res.push(part.slice()); + return; + } + + for (let j = i; j < s.length; j++) { + if (isPali(s, i, j)) { + part.push(s.slice(i, j + 1)); + dfs(j + 1); + part.pop(); + } + } + } + + dfs(0); + return res; + + function isPali(s, l, r) { + while (l < r) { + if (s[l] != s[r]) { + return false; + } + l = l + 1; + r = r - 1; + } + return true; + } +} diff --git a/javascript/133-Clone-Graph.js b/javascript/133-Clone-Graph.js index 9407e8f63..ad48ee387 100644 --- a/javascript/133-Clone-Graph.js +++ b/javascript/133-Clone-Graph.js @@ -10,28 +10,28 @@ * @param {Node} node * @return {Node} */ - var cloneGraph = function(node) { - let visited = {} - - let dfs = (node) => { - if(!node){ - return node; - } - - if(visited[node.val]){ - return visited[node.val] - } - - let copy = new Node(node.val); - - visited[node.val] = copy - - node.neighbors.forEach((n) => { - copy.neighbors.push(dfs(n)) - }) - - return copy +var cloneGraph = function (node) { + let visited = {}; + + let dfs = (node) => { + if (!node) { + return node; + } + + if (visited[node.val]) { + return visited[node.val]; } - - return dfs(node) -}; \ No newline at end of file + + let copy = new Node(node.val); + + visited[node.val] = copy; + + node.neighbors.forEach((n) => { + copy.neighbors.push(dfs(n)); + }); + + return copy; + }; + + return dfs(node); +}; diff --git a/javascript/136-Single-Number.js b/javascript/136-Single-Number.js index fddbfaf06..ae902b535 100644 --- a/javascript/136-Single-Number.js +++ b/javascript/136-Single-Number.js @@ -3,9 +3,9 @@ * @return {number} */ var singleNumber = function (nums) { - let xor_final = 0; - for (num of nums) { - xor_final = xor_final ^ num - } - return xor_final + let xor_final = 0; + for (num of nums) { + xor_final = xor_final ^ num; + } + return xor_final; }; diff --git a/javascript/138-Copy-List-with-Random-Pointer.js b/javascript/138-Copy-List-with-Random-Pointer.js index c1b39455b..dc6e30b17 100644 --- a/javascript/138-Copy-List-with-Random-Pointer.js +++ b/javascript/138-Copy-List-with-Random-Pointer.js @@ -12,7 +12,7 @@ var copyRandomList = function (head) { ptr = ptr.next; } - for (const [ oldptr, newptr ] of map) { + for (const [oldptr, newptr] of map) { newptr.next = oldptr.next && map.get(oldptr.next); newptr.random = oldptr.random && map.get(oldptr.random); } diff --git a/javascript/139-Word-Break.js b/javascript/139-Word-Break.js index b29b06f59..fa5be4fcd 100644 --- a/javascript/139-Word-Break.js +++ b/javascript/139-Word-Break.js @@ -1,19 +1,19 @@ -let wordBreak = function(s, wordDict) { - let dp = new Array(s.length + 1); - dp.fill(false); - dp[s.length] = true; +let wordBreak = function (s, wordDict) { + let dp = new Array(s.length + 1); + dp.fill(false); + dp[s.length] = true; - let word = ''; - for(let i = s.length - 1; i >= 0; i--) { - word = s[i] + word; + let word = ''; + for (let i = s.length - 1; i >= 0; i--) { + word = s[i] + word; - if(wordDict.includes(word) && i + word.length < dp.length) { - dp[i] = dp[i + word.length]; - word = ''; - } else { - dp[i] = false; - } + if (wordDict.includes(word) && i + word.length < dp.length) { + dp[i] = dp[i + word.length]; + word = ''; + } else { + dp[i] = false; } + } - return dp[0]; + return dp[0]; }; diff --git a/javascript/141-Linked-List-Cycle.js b/javascript/141-Linked-List-Cycle.js index d79850599..419f7b704 100644 --- a/javascript/141-Linked-List-Cycle.js +++ b/javascript/141-Linked-List-Cycle.js @@ -10,16 +10,16 @@ * @param {ListNode} head * @return {boolean} */ -var hasCycle = function(head) { - let set = new Set(); - while (head) { - if (set.has(head)) { - return true; - } else { - set.add(head); - head = head.next; - } +var hasCycle = function (head) { + let set = new Set(); + while (head) { + if (set.has(head)) { + return true; + } else { + set.add(head); + head = head.next; } - - return false; + } + + return false; }; diff --git a/javascript/143-Reorder-List.js b/javascript/143-Reorder-List.js index dbc5468a0..b7aee4677 100644 --- a/javascript/143-Reorder-List.js +++ b/javascript/143-Reorder-List.js @@ -9,42 +9,41 @@ * @param {ListNode} head * @return {void} Do not return anything, modify head in-place instead. */ -var reorderList = function(head) { - if (!head) { return }; - - let slow = head; - let fast = head; - - - // finding the middle of the linked list using 2 pters - while (fast && fast.next) { - slow = slow.next; - fast = fast.next.next; - } - - // reverse the second part of the list starting at slow - let prev = null - let curr = slow; - while (curr) { - let next = curr.next; - curr.next = prev; - prev = curr; - curr = next; - } // here prev is the head - - // merge two sorted lists (first one starts at head, second at prev) - let first = head; - let second = prev; - - while(second.next) { - temp = first.next; - first.next = second; - first = temp; - - temp = second.next; - second.next = first; - second = temp; - } - - +var reorderList = function (head) { + if (!head) { + return; + } + + let slow = head; + let fast = head; + + // finding the middle of the linked list using 2 pters + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + + // reverse the second part of the list starting at slow + let prev = null; + let curr = slow; + while (curr) { + let next = curr.next; + curr.next = prev; + prev = curr; + curr = next; + } // here prev is the head + + // merge two sorted lists (first one starts at head, second at prev) + let first = head; + let second = prev; + + while (second.next) { + temp = first.next; + first.next = second; + first = temp; + + temp = second.next; + second.next = first; + second = temp; + } }; diff --git a/javascript/1448-Count-Good-Nodes-in-Binary-Tree.js b/javascript/1448-Count-Good-Nodes-in-Binary-Tree.js index 922cbc8af..fb11fbe32 100644 --- a/javascript/1448-Count-Good-Nodes-in-Binary-Tree.js +++ b/javascript/1448-Count-Good-Nodes-in-Binary-Tree.js @@ -1,20 +1,20 @@ -function goodNodes(root) { - let total = 0; - - function traverse(node, prev) { - if (!node) return; - - if (node.left || node.right) { - traverse(node.left, Math.max(node.val, prev)); - traverse(node.right, Math.max(node.val, prev)); - } - - if (node.val >= prev) { - total += 1; - } - } - - traverse(root, root.val); - - return total; -} +function goodNodes(root) { + let total = 0; + + function traverse(node, prev) { + if (!node) return; + + if (node.left || node.right) { + traverse(node.left, Math.max(node.val, prev)); + traverse(node.right, Math.max(node.val, prev)); + } + + if (node.val >= prev) { + total += 1; + } + } + + traverse(root, root.val); + + return total; +} diff --git a/javascript/146-LRU-Cache.js b/javascript/146-LRU-Cache.js index 55af89dc9..ea4e09d6c 100644 --- a/javascript/146-LRU-Cache.js +++ b/javascript/146-LRU-Cache.js @@ -13,7 +13,7 @@ function LRUCache(capacity) { this.cacheMap = new Map(); } -/** +/** * @param {number} key * @return {number} */ @@ -27,8 +27,8 @@ LRUCache.prototype.get = function (key) { return value; }; -/** - * @param {number} key +/** + * @param {number} key * @param {number} value * @return {void} */ @@ -36,10 +36,7 @@ LRUCache.prototype.put = function (key, value) { if (this.cacheMap.has(key)) { this.cacheMap.delete(key); } else if (this.cacheMap.size === this.capacity) { - const leastRecentlyUsedKey = this.cacheMap - .keys() - .next() - .value; + const leastRecentlyUsedKey = this.cacheMap.keys().next().value; this.cacheMap.delete(leastRecentlyUsedKey); } this.cacheMap.set(key, value); @@ -53,106 +50,106 @@ LRUCache.prototype.put = function (key, value) { ////////////////////////////////////////////////////////////////////////////// class LRUNode { - /** - * @param {number} key - * @param {number} val - * @param {LRUNode=} next = `null` - * @constructor - */ - constructor(key, val, next = null) { - this.key = key; - this.val = val; - this.prev = null; - this.next = next; - } + /** + * @param {number} key + * @param {number} val + * @param {LRUNode=} next = `null` + * @constructor + */ + constructor(key, val, next = null) { + this.key = key; + this.val = val; + this.prev = null; + this.next = next; + } } class LRUCache { - /** - * @param {number} capacity - * @constructor - */ - constructor(capacity) { + /** + * @param {number} capacity + * @constructor + */ + constructor(capacity) { + this.head = null; + this.tail = null; + this.map = Object.create(null); + this.length = 0; + this.capacity = capacity; + } + + /** + * @param {number} key + * @return {number} + */ + get(key) { + if (!(key in this.map)) { + return -1; + } + this.makeMostRecent(key); + return this.map[key].val; + } + + /** + * @param {number} key + * @param {number} val + * @return {void} + */ + put(key, val) { + if (key in this.map) { + this.map[key].val = val; + this.makeMostRecent(key); + return; + } + + if (this.length === this.capacity) { + delete this.map[this.tail.key]; + if (this.head === this.tail) { this.head = null; this.tail = null; - this.map = Object.create(null); - this.length = 0; - this.capacity = capacity; + } else { + this.tail = this.tail.prev; + this.tail.next = null; + } + } else { + ++this.length; } - - /** - * @param {number} key - * @return {number} - */ - get(key) { - if (!(key in this.map)) { - return -1; - } - this.makeMostRecent(key); - return this.map[key].val; + + const node = new LRUNode(key, val, this.head); + + if (this.head) { + this.head.prev = node; + } else { + this.tail = node; } - - /** - * @param {number} key - * @param {number} val - * @return {void} - */ - put(key, val) { - if (key in this.map) { - this.map[key].val = val; - this.makeMostRecent(key); - return; - } - - if (this.length === this.capacity) { - delete this.map[this.tail.key]; - if (this.head === this.tail) { - this.head = null; - this.tail = null; - } else { - this.tail = this.tail.prev; - this.tail.next = null; - } - } else { - ++this.length; - } - - const node = new LRUNode(key, val, this.head); - - if (this.head) { - this.head.prev = node; - } else { - this.tail = node; - } - this.head = node; - - this.map[key] = node; + this.head = node; + + this.map[key] = node; + } + + /** + * @param {number} key + * @return {void} + */ + makeMostRecent(key) { + const node = this.map[key]; + + if (node === this.head) { + return node.val; } - - /** - * @param {number} key - * @return {void} - */ - makeMostRecent(key) { - const node = this.map[key]; - - if (node === this.head) { - return node.val; - } - - if (node.prev) { - node.prev.next = node.next; - } - if (node.next) { - node.next.prev = node.prev; - } - if (node === this.tail) { - this.tail = node.prev; - } - - node.prev = null; - node.next = this.head; - this.head.prev = node; - this.head = node; + + if (node.prev) { + node.prev.next = node.next; + } + if (node.next) { + node.next.prev = node.prev; + } + if (node === this.tail) { + this.tail = node.prev; } + + node.prev = null; + node.next = this.head; + this.head.prev = node; + this.head = node; + } } diff --git a/javascript/15-3Sum.js b/javascript/15-3Sum.js index 0bed71d32..1d3efff58 100644 --- a/javascript/15-3Sum.js +++ b/javascript/15-3Sum.js @@ -2,34 +2,42 @@ * @param {number[]} nums * @return {number[][]} */ -var threeSum = function(nums) { - let res = []; - let left = 0; - let right = nums.length - 1; - nums.sort((a,b) => { return a - b }) - - for (let i = 0; i < nums.length - 1; i++) { - if (nums[i] > 0) return res; - if (nums[i] === nums[i - 1]) continue; - - left = i + 1; - right = nums.length - 1; - let temp = 0; - - while (left < right) { - temp = nums[left] + nums[right] + nums[i]; - if (temp === 0) { - res.push([nums[i], nums[left], nums[right]]); - left++; - right--; - - while(nums[left] == nums[left - 1]) { left++ }; - - while (nums[right] == nums[right + 1]) { right-- }; - - } else if (temp > 0) { right-- } - else if (temp < 0) { left++ } +var threeSum = function (nums) { + let res = []; + let left = 0; + let right = nums.length - 1; + nums.sort((a, b) => { + return a - b; + }); + + for (let i = 0; i < nums.length - 1; i++) { + if (nums[i] > 0) return res; + if (nums[i] === nums[i - 1]) continue; + + left = i + 1; + right = nums.length - 1; + let temp = 0; + + while (left < right) { + temp = nums[left] + nums[right] + nums[i]; + if (temp === 0) { + res.push([nums[i], nums[left], nums[right]]); + left++; + right--; + + while (nums[left] == nums[left - 1]) { + left++; } + + while (nums[right] == nums[right + 1]) { + right--; + } + } else if (temp > 0) { + right--; + } else if (temp < 0) { + left++; + } } - return res; + } + return res; }; diff --git a/javascript/150-Evaluate-Reverse-Polish-Notation.js b/javascript/150-Evaluate-Reverse-Polish-Notation.js index 0296ae0a4..2964b411f 100644 --- a/javascript/150-Evaluate-Reverse-Polish-Notation.js +++ b/javascript/150-Evaluate-Reverse-Polish-Notation.js @@ -1,9 +1,9 @@ /** @const {!Object} */ const OPERATORS = { - '+': (a, b) => a + b, - '-': (a, b) => a - b, - '*': (a, b) => a * b, - '/': (a, b) => Math.trunc(a / b) + '+': (a, b) => a + b, + '-': (a, b) => a - b, + '*': (a, b) => a * b, + '/': (a, b) => Math.trunc(a / b), }; /** @@ -11,15 +11,15 @@ const OPERATORS = { * @return {number} */ function evalRPN(tokens) { - const stack = []; - for (const token of tokens) { - if (token in OPERATORS) { - const rhs = stack.pop(); - const lhs = stack.pop(); - stack.push(OPERATORS[token](lhs, rhs)); - } else { - stack.push(Number(token)); - } + const stack = []; + for (const token of tokens) { + if (token in OPERATORS) { + const rhs = stack.pop(); + const lhs = stack.pop(); + stack.push(OPERATORS[token](lhs, rhs)); + } else { + stack.push(Number(token)); } - return stack.pop(); + } + return stack.pop(); } diff --git a/javascript/152-Maximum-Product-Subarray.js b/javascript/152-Maximum-Product-Subarray.js index 64519e177..29d2dced0 100644 --- a/javascript/152-Maximum-Product-Subarray.js +++ b/javascript/152-Maximum-Product-Subarray.js @@ -2,19 +2,18 @@ * @param {number[]} nums * @return {number} */ -var maxProduct = function(nums) { - let result = nums[0]; - let prevMax = nums[0]; - let prevMin = nums[0]; - for(let i = 1; i < nums.length; i++) { - currMax = Math.max(nums[i], prevMax * nums[i], prevMin * nums[i]); - currMin = Math.min(nums[i], prevMax * nums[i], prevMin * nums[i]); - - prevMax = currMax; - prevMin = currMin; - - result = Math.max(currMax, result); - } - return result; +var maxProduct = function (nums) { + let result = nums[0]; + let prevMax = nums[0]; + let prevMin = nums[0]; + for (let i = 1; i < nums.length; i++) { + currMax = Math.max(nums[i], prevMax * nums[i], prevMin * nums[i]); + currMin = Math.min(nums[i], prevMax * nums[i], prevMin * nums[i]); + prevMax = currMax; + prevMin = currMin; + + result = Math.max(currMax, result); + } + return result; }; diff --git a/javascript/153-Find-Minimum-in-Rotated-Sorted-Array.js b/javascript/153-Find-Minimum-in-Rotated-Sorted-Array.js index 2c28650e2..f7c8ac63d 100644 --- a/javascript/153-Find-Minimum-in-Rotated-Sorted-Array.js +++ b/javascript/153-Find-Minimum-in-Rotated-Sorted-Array.js @@ -2,16 +2,16 @@ * @param {number[]} nums * @return {number} */ -var findMin = function(nums) { - let left = 0; - let right = nums.length - 1; - while (right > left) { - let mid = Math.floor((right + left) / 2); - if (nums[mid] > nums[right]) { - left = mid + 1; - } else { - right = mid; - } +var findMin = function (nums) { + let left = 0; + let right = nums.length - 1; + while (right > left) { + let mid = Math.floor((right + left) / 2); + if (nums[mid] > nums[right]) { + left = mid + 1; + } else { + right = mid; } - return nums[left]; + } + return nums[left]; }; diff --git a/javascript/155-Min-Stack.js b/javascript/155-Min-Stack.js index 188b1bd5a..2e3dabdfa 100644 --- a/javascript/155-Min-Stack.js +++ b/javascript/155-Min-Stack.js @@ -11,46 +11,49 @@ ////////////////////////////////////////////////////////////////////////////// class MinStack { - /** - * @constructor - */ - constructor() { - this.mainStack = []; - this.minStack = []; - } + /** + * @constructor + */ + constructor() { + this.mainStack = []; + this.minStack = []; + } - /** - * @param {number} val - * @return {void} - */ - push(val) { - this.mainStack.push(val); - if (!this.minStack.length || val <= this.minStack[this.minStack.length - 1]) { - this.minStack.push(val); - } + /** + * @param {number} val + * @return {void} + */ + push(val) { + this.mainStack.push(val); + if ( + !this.minStack.length || + val <= this.minStack[this.minStack.length - 1] + ) { + this.minStack.push(val); } + } - /** - * @return {void} - */ - pop() { - const val = this.mainStack.pop(); - if (val === this.minStack[this.minStack.length - 1]) { - this.minStack.pop(); - } + /** + * @return {void} + */ + pop() { + const val = this.mainStack.pop(); + if (val === this.minStack[this.minStack.length - 1]) { + this.minStack.pop(); } + } - /** - * @return {number} - */ - top() { - return this.mainStack[this.mainStack.length - 1]; - } + /** + * @return {number} + */ + top() { + return this.mainStack[this.mainStack.length - 1]; + } - /** - * @return {number} - */ - getMin() { - return this.minStack[this.minStack.length - 1]; - } + /** + * @return {number} + */ + getMin() { + return this.minStack[this.minStack.length - 1]; + } } diff --git a/javascript/160-Intersection-of-Two-Linked-Lists.js b/javascript/160-Intersection-of-Two-Linked-Lists.js index e7f51395d..8615b0878 100644 --- a/javascript/160-Intersection-of-Two-Linked-Lists.js +++ b/javascript/160-Intersection-of-Two-Linked-Lists.js @@ -11,13 +11,13 @@ * @param {ListNode} headB * @return {ListNode} */ -var getIntersectionNode = function(headA, headB) { - let a = headA; - let b = headB; - while (a !== b) { - a = a === null ? headB : a.next; - b = b === null ? headA : b.next; - } - - return a; +var getIntersectionNode = function (headA, headB) { + let a = headA; + let b = headB; + while (a !== b) { + a = a === null ? headB : a.next; + b = b === null ? headA : b.next; + } + + return a; }; diff --git a/javascript/167-Two-Sum-II.js b/javascript/167-Two-Sum-II.js index 57fece92d..522d74e31 100644 --- a/javascript/167-Two-Sum-II.js +++ b/javascript/167-Two-Sum-II.js @@ -3,14 +3,14 @@ * @param {number} target * @return {number[]} */ - var twoSum = function(numbers, target) { - let start = 0; - let end = numbers.length -1; - while (start < end) { - let currSum = numbers[start] + numbers[end]; - if (currSum > target) end--; - else if (currSum < target) start++; - else return [start +1, end +1]; - }; - return []; +var twoSum = function (numbers, target) { + let start = 0; + let end = numbers.length - 1; + while (start < end) { + let currSum = numbers[start] + numbers[end]; + if (currSum > target) end--; + else if (currSum < target) start++; + else return [start + 1, end + 1]; + } + return []; }; diff --git a/javascript/17-Letter-Combinations-of-a-Phone-Number.js b/javascript/17-Letter-Combinations-of-a-Phone-Number.js index a30304ff0..6684161c5 100644 --- a/javascript/17-Letter-Combinations-of-a-Phone-Number.js +++ b/javascript/17-Letter-Combinations-of-a-Phone-Number.js @@ -1,31 +1,31 @@ -function letterCombinations(digits) { - let res = []; - - const digitToChar = { - 2: "abc", - 3: "def", - 4: "ghi", - 5: "jkl", - 6: "mno", - 7: "qprs", - 8: "tuv", - 9: "wxyz", - }; - - function backtrack(i, curStr) { - if (curStr.length === digits.length) { - res.push(curStr); - return; - } - - for (const c of digitToChar[digits[i]]) { - backtrack(i + 1, curStr + c); - } - } - - if (digits) { - backtrack(0, ""); - } - - return res; -} +function letterCombinations(digits) { + let res = []; + + const digitToChar = { + 2: 'abc', + 3: 'def', + 4: 'ghi', + 5: 'jkl', + 6: 'mno', + 7: 'qprs', + 8: 'tuv', + 9: 'wxyz', + }; + + function backtrack(i, curStr) { + if (curStr.length === digits.length) { + res.push(curStr); + return; + } + + for (const c of digitToChar[digits[i]]) { + backtrack(i + 1, curStr + c); + } + } + + if (digits) { + backtrack(0, ''); + } + + return res; +} diff --git a/javascript/19-Remove-Nth-Node-From-End-of-List.js b/javascript/19-Remove-Nth-Node-From-End-of-List.js index e52e76058..8dfd1ad05 100644 --- a/javascript/19-Remove-Nth-Node-From-End-of-List.js +++ b/javascript/19-Remove-Nth-Node-From-End-of-List.js @@ -10,23 +10,24 @@ * @param {number} n * @return {ListNode} */ -var removeNthFromEnd = function(head, n) { - let currNode = head; - let nodeBeforeN = head; - - for (let i = 0; i < n; i++) { - currNode = currNode.next; - } - - if (!currNode) { return head.next } - - while (currNode.next) { - nodeBeforeN = nodeBeforeN.next; - currNode = currNode.next; - } - - nodeBeforeN.next = nodeBeforeN.next.next; - - return head; - +var removeNthFromEnd = function (head, n) { + let currNode = head; + let nodeBeforeN = head; + + for (let i = 0; i < n; i++) { + currNode = currNode.next; + } + + if (!currNode) { + return head.next; + } + + while (currNode.next) { + nodeBeforeN = nodeBeforeN.next; + currNode = currNode.next; + } + + nodeBeforeN.next = nodeBeforeN.next.next; + + return head; }; diff --git a/javascript/190-Reverse-Bits.js b/javascript/190-Reverse-Bits.js index 7084f3005..bd89817ec 100644 --- a/javascript/190-Reverse-Bits.js +++ b/javascript/190-Reverse-Bits.js @@ -1,13 +1,13 @@ -var reverseBits = function(n) { - let result = 0b0; - let curr = n; +var reverseBits = function (n) { + let result = 0b0; + let curr = n; - for (let i = 0; i < 32; i++) { - const lastBit = curr & 0b1; - result = result << 1; - result = result | lastBit; - curr = curr >> 1; - } + for (let i = 0; i < 32; i++) { + const lastBit = curr & 0b1; + result = result << 1; + result = result | lastBit; + curr = curr >> 1; + } - return result >>> 0; + return result >>> 0; }; diff --git a/javascript/191-Number-of-1-bits.js b/javascript/191-Number-of-1-bits.js index ba44d4f22..191b57608 100644 --- a/javascript/191-Number-of-1-bits.js +++ b/javascript/191-Number-of-1-bits.js @@ -3,10 +3,10 @@ * @return {number} */ var hammingWeight = function (n) { - let output = 0; - while (n != 0) { - n &= (n - 1); - output++; - } - return output; + let output = 0; + while (n != 0) { + n &= n - 1; + output++; + } + return output; }; diff --git a/javascript/198-House-Robber.js b/javascript/198-House-Robber.js index 45962c32c..c83e022ac 100644 --- a/javascript/198-House-Robber.js +++ b/javascript/198-House-Robber.js @@ -1,12 +1,12 @@ -function rob(nums) { - let rob1 = 0; - let rob2 = 0; - - for (const n of nums) { - let temp = Math.max(n + rob1, rob2); - rob1 = rob2; - rob2 = temp; - } - - return rob2; -} +function rob(nums) { + let rob1 = 0; + let rob2 = 0; + + for (const n of nums) { + let temp = Math.max(n + rob1, rob2); + rob1 = rob2; + rob2 = temp; + } + + return rob2; +} diff --git a/javascript/199-binary-tree-right-side-view.js b/javascript/199-binary-tree-right-side-view.js index 24632d04f..3e0faedc0 100644 --- a/javascript/199-binary-tree-right-side-view.js +++ b/javascript/199-binary-tree-right-side-view.js @@ -10,26 +10,26 @@ * @param {TreeNode} root * @return {number[]} */ - var rightSideView = function(root) { - let result = [] - let queue = [] - - if (root === null) { - return [] +var rightSideView = function (root) { + let result = []; + let queue = []; + + if (root === null) { + return []; + } + + queue.push(root); + + while (queue.length > 0) { + let length = queue.length; + for (let i = 0; i < length; i++) { + let node = queue.shift(); + if (i === length - 1) { + result.push(node.val); + } + if (node.left !== null) queue.push(node.left); + if (node.right !== null) queue.push(node.right); } - - queue.push(root) - - while(queue.length > 0){ - let length = queue.length - for (let i = 0 ; i < length ; i++) { - let node = queue.shift() - if (i === length - 1) { - result.push(node.val) - } - if (node.left !== null) queue.push(node.left) - if (node.right !== null) queue.push(node.right) - } - } - return result -}; \ No newline at end of file + } + return result; +}; diff --git a/javascript/2-Add-Two-Numbers.js b/javascript/2-Add-Two-Numbers.js index 09de2f7e5..ef79e9201 100644 --- a/javascript/2-Add-Two-Numbers.js +++ b/javascript/2-Add-Two-Numbers.js @@ -1,27 +1,27 @@ -function addTwoNumbers(l1, l2) { - let temp1 = l1; - let temp2 = l2; - - let dummy = new ListNode(0); - let merged = dummy; - - let carry = 0; - - while (temp1 || temp2) { - let sum = (temp1?.val || 0) + (temp2?.val || 0) + carry; - carry = Math.floor(sum / 10); - sum = sum % 10; - - merged.next = new ListNode(sum); - merged = merged.next; - - if (temp1) temp1 = temp1?.next; - if (temp2) temp2 = temp2?.next; - } - - if (carry > 0) { - merged.next = new ListNode(carry); - } - - return dummy.next; -} +function addTwoNumbers(l1, l2) { + let temp1 = l1; + let temp2 = l2; + + let dummy = new ListNode(0); + let merged = dummy; + + let carry = 0; + + while (temp1 || temp2) { + let sum = (temp1?.val || 0) + (temp2?.val || 0) + carry; + carry = Math.floor(sum / 10); + sum = sum % 10; + + merged.next = new ListNode(sum); + merged = merged.next; + + if (temp1) temp1 = temp1?.next; + if (temp2) temp2 = temp2?.next; + } + + if (carry > 0) { + merged.next = new ListNode(carry); + } + + return dummy.next; +} diff --git a/javascript/20-Valid-Parentheses.js b/javascript/20-Valid-Parentheses.js index 149722b31..87b385f48 100644 --- a/javascript/20-Valid-Parentheses.js +++ b/javascript/20-Valid-Parentheses.js @@ -2,31 +2,30 @@ * @param {string} s * @return {boolean} */ -var isValid = function(s) { - - let closeMap = { - '}' :'{', - ')' : '(', - ']' : '[' - }; - - let charStack = []; - - if (!s) return false; - - for (let i = 0; i < s.length; i++) { - let curr = s.charAt(i); - // check if closing bracket - if (closeMap[curr]) { - topElement = (charStack.length === 0) ? '#' : charStack.pop(); - if (topElement !== closeMap[curr]) { - return false; - } - // opening bracket case - } else { - charStack.push(curr); - } +var isValid = function (s) { + let closeMap = { + '}': '{', + ')': '(', + ']': '[', + }; + + let charStack = []; + + if (!s) return false; + + for (let i = 0; i < s.length; i++) { + let curr = s.charAt(i); + // check if closing bracket + if (closeMap[curr]) { + topElement = charStack.length === 0 ? '#' : charStack.pop(); + if (topElement !== closeMap[curr]) { + return false; + } + // opening bracket case + } else { + charStack.push(curr); } - - return charStack.length === 0; + } + + return charStack.length === 0; }; diff --git a/javascript/200-Number-of-Islands.js b/javascript/200-Number-of-Islands.js index 97daebf35..c53c453b5 100644 --- a/javascript/200-Number-of-Islands.js +++ b/javascript/200-Number-of-Islands.js @@ -35,11 +35,17 @@ var numIslands = function (grid) { // Version 2 (Easier to understand/read) function dfs(grid, i, j) { - if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] === "0") { + if ( + i < 0 || + i >= grid.length || + j < 0 || + j >= grid[0].length || + grid[i][j] === '0' + ) { return; } - grid[i][j] = "0"; + grid[i][j] = '0'; dfs(grid, i + 1, j); dfs(grid, i - 1, j); dfs(grid, i, j + 1); @@ -51,11 +57,11 @@ var numIslands = function (grid) { for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[0].length; j++) { - if (grid[i][j] === "1") { + if (grid[i][j] === '1') { count += 1; dfs(grid, i, j); } } } return count; -}; \ No newline at end of file +}; diff --git a/javascript/202-Happy-Number.js b/javascript/202-Happy-Number.js index 121ec32af..d8a0c3bb4 100644 --- a/javascript/202-Happy-Number.js +++ b/javascript/202-Happy-Number.js @@ -1,25 +1,25 @@ -function isHappy(n) { - const visit = new Set(); - - while (!visit.has(n)) { - visit.add(n); - n = sumOfSquares(n); - - if (n == 1) return true; - } - - return false; -} - -function sumOfSquares(n) { - let output = 0; - - while (n) { - let digit = n % 10; - digit = digit ** 2; - output += digit; - n = Math.floor(n / 10); - } - - return output; -} +function isHappy(n) { + const visit = new Set(); + + while (!visit.has(n)) { + visit.add(n); + n = sumOfSquares(n); + + if (n == 1) return true; + } + + return false; +} + +function sumOfSquares(n) { + let output = 0; + + while (n) { + let digit = n % 10; + digit = digit ** 2; + output += digit; + n = Math.floor(n / 10); + } + + return output; +} diff --git a/javascript/206-Reverse-Linked-List.js b/javascript/206-Reverse-Linked-List.js index 15bbbf0ff..865a17e55 100644 --- a/javascript/206-Reverse-Linked-List.js +++ b/javascript/206-Reverse-Linked-List.js @@ -9,15 +9,15 @@ * @param {ListNode} head * @return {ListNode} */ -var reverseList = function(head) { - let prev = null; - - while (head) { - let next = head.next; - head.next = prev; - prev = head; - head = next; - } - - return prev; +var reverseList = function (head) { + let prev = null; + + while (head) { + let next = head.next; + head.next = prev; + prev = head; + head = next; + } + + return prev; }; diff --git a/javascript/207-canFinish.js b/javascript/207-canFinish.js index fe02f1f96..83aaaa27d 100644 --- a/javascript/207-canFinish.js +++ b/javascript/207-canFinish.js @@ -35,4 +35,4 @@ function canFinish(numCourses, preq) { if (!explore(i)) return false; } return true; -}; \ No newline at end of file +} diff --git a/javascript/208-Implement-Trie.js b/javascript/208-Implement-Trie.js index 784e9c67c..1de957f5b 100644 --- a/javascript/208-Implement-Trie.js +++ b/javascript/208-Implement-Trie.js @@ -1,4 +1,4 @@ -/** +/** * Your Trie object will be instantiated and called as such: * var obj = new Trie() * obj.insert(word) @@ -7,53 +7,53 @@ */ class TrieNode { - constructor() { - this.children = {}; - this.isWord = false; - } + constructor() { + this.children = {}; + this.isWord = false; + } } class Trie { - constructor () { - this.root = new TrieNode(); - } - - /* Time O(N) | Space O(N) */ - insert (word, node = this.root) { - for (const char of word) { - const child = node.children[char] || new TrieNode(); + constructor() { + this.root = new TrieNode(); + } - node.children[char] = child; + /* Time O(N) | Space O(N) */ + insert(word, node = this.root) { + for (const char of word) { + const child = node.children[char] || new TrieNode(); - node = child; - } + node.children[char] = child; - node.isWord = true; + node = child; } - /* Time O(N) | Space O(1) */ - search (word, node = this.root) { - for (const char of word) { - const child = node.children[char] || null; + node.isWord = true; + } - if (!child) return false; + /* Time O(N) | Space O(1) */ + search(word, node = this.root) { + for (const char of word) { + const child = node.children[char] || null; - node = child; - } + if (!child) return false; - return node.isWord; + node = child; } - /* Time O(N) | Space O(1) */ - startsWith (prefix, node = this.root) { - for (const char of prefix) { - const child = node.children[char] || null; + return node.isWord; + } - if (!child) return false; + /* Time O(N) | Space O(1) */ + startsWith(prefix, node = this.root) { + for (const char of prefix) { + const child = node.children[char] || null; - node = child; - } + if (!child) return false; - return true; + node = child; } -}; + + return true; + } +} diff --git a/javascript/21-Merge-Two-Sorted-Lists.js b/javascript/21-Merge-Two-Sorted-Lists.js index a9e155607..fa451974b 100644 --- a/javascript/21-Merge-Two-Sorted-Lists.js +++ b/javascript/21-Merge-Two-Sorted-Lists.js @@ -10,19 +10,19 @@ * @param {ListNode} list2 * @return {ListNode} */ -var mergeTwoLists = function(l1, l2) { - let nullNode = { val : 0, next : null}; - let prev = nullNode; - while (l1 && l2) { - if (l1.val >= l2.val) { - prev.next = l2; - l2 = l2.next; - } else { - prev.next = l1; - l1 = l1.next; - } - prev = prev.next; +var mergeTwoLists = function (l1, l2) { + let nullNode = { val: 0, next: null }; + let prev = nullNode; + while (l1 && l2) { + if (l1.val >= l2.val) { + prev.next = l2; + l2 = l2.next; + } else { + prev.next = l1; + l1 = l1.next; } - prev.next = l1 || l2; - return nullNode.next; + prev = prev.next; + } + prev.next = l1 || l2; + return nullNode.next; }; diff --git a/javascript/210-Course-Schedule-II.js b/javascript/210-Course-Schedule-II.js index e1ad55306..d3952e3ac 100644 --- a/javascript/210-Course-Schedule-II.js +++ b/javascript/210-Course-Schedule-II.js @@ -3,22 +3,22 @@ * @param {number[][]} prerequisites * @return {number[]} */ - var findOrder = function(numCourses, prerequisites) { - const prereq = []; - for (let i = 0; i < numCourses; i++) { - prereq[i] = []; - }; +var findOrder = function (numCourses, prerequisites) { + const prereq = []; + for (let i = 0; i < numCourses; i++) { + prereq[i] = []; + } for (const [crs, pre] of prerequisites) { prereq[crs].push(pre); - }; - - const output = []; + } + + const output = []; const visit = new Set(); const cycle = new Set(); - function dfs(course) { + function dfs(course) { if (cycle.has(course)) return false; if (visit.has(course)) return true; - + cycle.add(course); for (const pre of prereq[course]) { if (!dfs(pre)) return false; @@ -27,10 +27,10 @@ visit.add(course); output.push(course); return true; - }; + } - for (let j = 0; j < numCourses; j++) { - if (!dfs(j)) return []; - }; - return output; -}; \ No newline at end of file + for (let j = 0; j < numCourses; j++) { + if (!dfs(j)) return []; + } + return output; +}; diff --git a/javascript/211-Design-Add-and-Search-Words-Data-Structure.js b/javascript/211-Design-Add-and-Search-Words-Data-Structure.js index c18ed1937..1c090dbd1 100644 --- a/javascript/211-Design-Add-and-Search-Words-Data-Structure.js +++ b/javascript/211-Design-Add-and-Search-Words-Data-Structure.js @@ -1,60 +1,60 @@ -/** +/** * Your WordDictionary object will be instantiated and called as such: * var obj = new WordDictionary() * obj.addWord(word) * var param_2 = obj.search(word) */ - class TrieNode { - constructor() { - this.children = {}; - this.isWord = false; - } -}; +class TrieNode { + constructor() { + this.children = {}; + this.isWord = false; + } +} class WordDictionary { - constructor() { - this.root = new TrieNode(); - } - - /* Time O(N) | Space O(N) */ - addWord (word, node = this.root) { - for (const char of word) { - const child = node.children[char] || new TrieNode(); + constructor() { + this.root = new TrieNode(); + } - node.children[char] = child; + /* Time O(N) | Space O(N) */ + addWord(word, node = this.root) { + for (const char of word) { + const child = node.children[char] || new TrieNode(); - node = child; - } + node.children[char] = child; - node.isWord = true; + node = child; } - /* Time O(N) | Space O(N) */ - search (word) { - return this.dfs(word, this.root, 0); - } + node.isWord = true; + } - dfs (word, node, level) { - if (!node) return false; + /* Time O(N) | Space O(N) */ + search(word) { + return this.dfs(word, this.root, 0); + } - const isWord = level === word.length; - if (isWord) return node.isWord; + dfs(word, node, level) { + if (!node) return false; - const isWildCard = word[level] === '.'; - if (isWildCard) return this.hasWildCard(word, node, level); + const isWord = level === word.length; + if (isWord) return node.isWord; - return this.dfs(word, node.children[word[level]], (level + 1)); - } + const isWildCard = word[level] === '.'; + if (isWildCard) return this.hasWildCard(word, node, level); - hasWildCard (word, node, level) { - for (const char of Object.keys(node.children)) { - const child = node.children[char]; + return this.dfs(word, node.children[word[level]], level + 1); + } - const hasWord = this.dfs(word, child, (level + 1)); - if (hasWord) return true; - } + hasWildCard(word, node, level) { + for (const char of Object.keys(node.children)) { + const child = node.children[char]; - return false; + const hasWord = this.dfs(word, child, level + 1); + if (hasWord) return true; } + + return false; + } } diff --git a/javascript/212-Word-Search-ii.js b/javascript/212-Word-Search-ii.js index 29cba4933..9a4ddbec5 100644 --- a/javascript/212-Word-Search-ii.js +++ b/javascript/212-Word-Search-ii.js @@ -4,100 +4,99 @@ * Time O((ROWS * COLS) * (4 * (3 ^ (WORDS - 1)))) | Space O(N) * @return {string[]} */ - var findWords = function(board, words) { - return new Trie(words).searchBoard(board); -} +var findWords = function (board, words) { + return new Trie(words).searchBoard(board); +}; class TrieNode { - constructor() { - this.children = {}; - this.word = ''; - } + constructor() { + this.children = {}; + this.word = ''; + } } class Trie { - constructor(words) { - this.root = new TrieNode(); - words.forEach((word) => this.insert(word)); - } + constructor(words) { + this.root = new TrieNode(); + words.forEach((word) => this.insert(word)); + } - /* Time O(N) | Space O(N) */ - insert (word, node = this.root) { - for (const char of word) { - const child = node.children[char] || new TrieNode(); + /* Time O(N) | Space O(N) */ + insert(word, node = this.root) { + for (const char of word) { + const child = node.children[char] || new TrieNode(); - node.children[char] = child; + node.children[char] = child; - node = child; - } - - node.word = word; + node = child; } - /* Time O((ROWS * COLS) * (4 * (3 ^ (WORDS - 1)))) | Space O(N) */ - searchBoard (board, node = this.root, words = []) { - const [ rows, cols ] = [ board.length, board[0].length ]; - - for (let row = 0; row < rows; row++) { - for (let col = 0; col < cols; col++) { - this.dfs(board, row, rows, col, cols, node, words); - } - } - - return words; - } + node.word = word; + } - dfs (board, row, rows, col, cols, node, words) { - const char = board[row][col]; - const child = node.children[char] || null; + /* Time O((ROWS * COLS) * (4 * (3 ^ (WORDS - 1)))) | Space O(N) */ + searchBoard(board, node = this.root, words = []) { + const [rows, cols] = [board.length, board[0].length]; - if (this.canSkip(char, child)) return; - - node = child; - this.checkWord(node, words); - this.backTrack(board, row, rows, col, cols, node, words); + for (let row = 0; row < rows; row++) { + for (let col = 0; col < cols; col++) { + this.dfs(board, row, rows, col, cols, node, words); + } } - - - canSkip (char, child) { - const hasSeen = char === '#'; - const isMissingChild = !child; - - return hasSeen || isMissingChild; - } - - checkWord (node, words) { - if (!node.word.length) return; - words.push(node.word); - node.word = ''; - } - - backTrack (board, row, rows, col, cols, node, words) { - const char = board[row][col]; - - board[row][col] = '#'; + return words; + } - for (const [ _row, _col ] of this.getNeighbors(row, rows, col, cols)) { - this.dfs(board, _row, rows, _col, cols, node, words); - } + dfs(board, row, rows, col, cols, node, words) { + const char = board[row][col]; + const child = node.children[char] || null; - board[row][col] = char; - } - - getNeighbors (row, rows, col, cols) { - return [ - [row - 1, col], - [row + 1, col], - [row, col - 1], - [row, col + 1] - ].filter(([ _row, _col ]) => !this.isOutOfBounds(_row, rows, _col, cols)); - } + if (this.canSkip(char, child)) return; + + node = child; + this.checkWord(node, words); + this.backTrack(board, row, rows, col, cols, node, words); + } - isOutOfBounds(row, rows, col, cols) { - const isRowOut = row < 0 || rows <= row; - const isColOut = col < 0 || cols <= col; + canSkip(char, child) { + const hasSeen = char === '#'; + const isMissingChild = !child; - return isRowOut || isColOut; + return hasSeen || isMissingChild; + } + + checkWord(node, words) { + if (!node.word.length) return; + + words.push(node.word); + node.word = ''; + } + + backTrack(board, row, rows, col, cols, node, words) { + const char = board[row][col]; + + board[row][col] = '#'; + + for (const [_row, _col] of this.getNeighbors(row, rows, col, cols)) { + this.dfs(board, _row, rows, _col, cols, node, words); } + + board[row][col] = char; + } + + getNeighbors(row, rows, col, cols) { + return [ + [row - 1, col], + [row + 1, col], + [row, col - 1], + [row, col + 1], + ].filter(([_row, _col]) => !this.isOutOfBounds(_row, rows, _col, cols)); + } + + isOutOfBounds(row, rows, col, cols) { + const isRowOut = row < 0 || rows <= row; + const isColOut = col < 0 || cols <= col; + + return isRowOut || isColOut; + } } diff --git a/javascript/213-House-Robber-II.js b/javascript/213-House-Robber-II.js index 2264be082..a2d2c0d72 100644 --- a/javascript/213-House-Robber-II.js +++ b/javascript/213-House-Robber-II.js @@ -2,20 +2,20 @@ * @param {number[]} nums * @return {number} */ - var rob = function(nums) { - const n = nums.length; - if (n == 1) return nums[0]; +var rob = function (nums) { + const n = nums.length; + if (n == 1) return nums[0]; - function houseRobber(start, end) { - let first = 0; - let second = nums[start]; - for (let i = start +1; i < end; i++) { - let temp = Math.max(first + nums[i], second); - first = second; - second = temp; - }; - return second; - }; + function houseRobber(start, end) { + let first = 0; + let second = nums[start]; + for (let i = start + 1; i < end; i++) { + let temp = Math.max(first + nums[i], second); + first = second; + second = temp; + } + return second; + } - return Math.max(houseRobber(0, n-1), houseRobber(1, n)); -}; \ No newline at end of file + return Math.max(houseRobber(0, n - 1), houseRobber(1, n)); +}; diff --git a/javascript/217-Contains-Duplicate.js b/javascript/217-Contains-Duplicate.js index e9912889e..cb1b7d203 100644 --- a/javascript/217-Contains-Duplicate.js +++ b/javascript/217-Contains-Duplicate.js @@ -4,28 +4,28 @@ */ //First method using Map() (exit early if true) -var containsDuplicate = function(nums) { - const numsSet = new Set() - for(const i of nums){ - if(numsSet.has(i)){ - return true - } - numsSet.add(i) +var containsDuplicate = function (nums) { + const numsSet = new Set(); + for (const i of nums) { + if (numsSet.has(i)) { + return true; } - return false; + numsSet.add(i); + } + return false; }; //Second method using Map() (Has to map entire array but code is more readable) -var containsDuplicate = function(nums) { - //create a new hashmap with all the items in the array. Any duplicates will be removed. - const totalWithoutDuplicates = new Map(nums.map((i) => [i])); - - //check if the size of the initial array is larger than the new hashmap. - return totalWithoutDuplicates.size !== nums.length; +var containsDuplicate = function (nums) { + //create a new hashmap with all the items in the array. Any duplicates will be removed. + const totalWithoutDuplicates = new Map(nums.map((i) => [i])); + + //check if the size of the initial array is larger than the new hashmap. + return totalWithoutDuplicates.size !== nums.length; }; //Third method using Set() (Fastest runtime at 91.95% and very readable code) -var containsDuplicate = function(nums) { - //Pass the array into a Set() (which removes duplicates) and then compare its size to the original array. - return new Set(nums).size !== nums.length; +var containsDuplicate = function (nums) { + //Pass the array into a Set() (which removes duplicates) and then compare its size to the original array. + return new Set(nums).size !== nums.length; }; diff --git a/javascript/22-Generate-Parentheses.js b/javascript/22-Generate-Parentheses.js index c497b63d5..b729fcdb9 100644 --- a/javascript/22-Generate-Parentheses.js +++ b/javascript/22-Generate-Parentheses.js @@ -1,33 +1,33 @@ -/** - * https://leetcode.com/problems/generate-parentheses/ - * - * @param {number} n - * @return {string[]} - */ -var generateParenthesis = function(n) { - const combinations = [] - const currentCombination = [] - - function exploreParens(opensRemaining, closesAvailable) { - if (currentCombination.length == n * 2) { - combinations.push(currentCombination.join("")) - return - } - - if (opensRemaining) { - currentCombination.push("(") - exploreParens(opensRemaining - 1, closesAvailable + 1) - currentCombination.pop() - } - - if (closesAvailable) { - currentCombination.push(")") - exploreParens(opensRemaining, closesAvailable - 1) - currentCombination.pop() - } - } - - exploreParens(n, 0) - - return combinations -}; +/** + * https://leetcode.com/problems/generate-parentheses/ + * + * @param {number} n + * @return {string[]} + */ +var generateParenthesis = function (n) { + const combinations = []; + const currentCombination = []; + + function exploreParens(opensRemaining, closesAvailable) { + if (currentCombination.length == n * 2) { + combinations.push(currentCombination.join('')); + return; + } + + if (opensRemaining) { + currentCombination.push('('); + exploreParens(opensRemaining - 1, closesAvailable + 1); + currentCombination.pop(); + } + + if (closesAvailable) { + currentCombination.push(')'); + exploreParens(opensRemaining, closesAvailable - 1); + currentCombination.pop(); + } + } + + exploreParens(n, 0); + + return combinations; +}; diff --git a/javascript/226-Invert-Binary-Tree.js b/javascript/226-Invert-Binary-Tree.js index 33888e1d4..b96fb71e5 100644 --- a/javascript/226-Invert-Binary-Tree.js +++ b/javascript/226-Invert-Binary-Tree.js @@ -10,11 +10,10 @@ * @param {TreeNode} root * @return {TreeNode} */ -var invertTree = function(root) { - if (!root) return root; - let left = root.left; - root.left = invertTree(root.right); - root.right = invertTree(left); - return root; - +var invertTree = function (root) { + if (!root) return root; + let left = root.left; + root.left = invertTree(root.right); + root.right = invertTree(left); + return root; }; diff --git a/javascript/23-Merge-K-Sorted-Lists.js b/javascript/23-Merge-K-Sorted-Lists.js index 472a78762..ba707f9e9 100644 --- a/javascript/23-Merge-K-Sorted-Lists.js +++ b/javascript/23-Merge-K-Sorted-Lists.js @@ -16,8 +16,7 @@ var merge = function (l1, l2) { if (l2) current.next = l2; return tempNode.next; -} - +}; var mergeKLists = function (lists) { let root = lists[0]; @@ -26,4 +25,4 @@ var mergeKLists = function (lists) { root = merge(root, lists[i]); } return root || null; -}; \ No newline at end of file +}; diff --git a/javascript/230-Kth-Smallest-Element-in-a-BST.js b/javascript/230-Kth-Smallest-Element-in-a-BST.js index f16bdc6a9..a0541c7dc 100644 --- a/javascript/230-Kth-Smallest-Element-in-a-BST.js +++ b/javascript/230-Kth-Smallest-Element-in-a-BST.js @@ -1,21 +1,21 @@ -function kthSmallest(root, k) { - let n = 0; - const stack = []; - let cur = root; - - while (cur || stack) { - while (cur) { - stack.push(cur); - cur = cur.left; - } - - cur = stack.pop(); - n += 1; - - if (n == k) { - return cur.val; - } - - cur = cur?.right; - } -} +function kthSmallest(root, k) { + let n = 0; + const stack = []; + let cur = root; + + while (cur || stack) { + while (cur) { + stack.push(cur); + cur = cur.left; + } + + cur = stack.pop(); + n += 1; + + if (n == k) { + return cur.val; + } + + cur = cur?.right; + } +} diff --git a/javascript/234-Palindrome-Linked-List.js b/javascript/234-Palindrome-Linked-List.js index 560f2ec2c..3b3baeccf 100644 --- a/javascript/234-Palindrome-Linked-List.js +++ b/javascript/234-Palindrome-Linked-List.js @@ -9,35 +9,35 @@ * @param {ListNode} head * @return {boolean} */ -var isPalindrome = function(head) { - // find mid point - let slow = head; - let fast = head; - while (fast && fast.next) { - slow = slow.next; - fast = fast.next.next; +var isPalindrome = function (head) { + // find mid point + let slow = head; + let fast = head; + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + + // reverse 2nd half + let curr = slow; + let prev = null; + while (curr) { + let next = curr.next; + curr.next = prev; + prev = curr; + curr = next; + } + let head2 = prev; + + // compare both halfs + while (head && head2) { + if (head.val !== head2.val) { + return false; } - - // reverse 2nd half - let curr = slow; - let prev = null; - while (curr) { - let next = curr.next; - curr.next = prev; - prev = curr; - curr = next; - } - let head2 = prev; - - // compare both halfs - while (head && head2) { - if (head.val !== head2.val) { - return false; - } - - head = head.next; - head2 = head2.next; - } - - return true; + + head = head.next; + head2 = head2.next; + } + + return true; }; diff --git a/javascript/235-lowest-common-ancestor-of-a-binary-search-tree.js b/javascript/235-lowest-common-ancestor-of-a-binary-search-tree.js index 414983878..d7b5d0a62 100644 --- a/javascript/235-lowest-common-ancestor-of-a-binary-search-tree.js +++ b/javascript/235-lowest-common-ancestor-of-a-binary-search-tree.js @@ -12,14 +12,14 @@ * @param {TreeNode} q * @return {TreeNode} */ - var lowestCommonAncestor = function(root, p, q) { - while(root !== null) { - if (root.val < p.val && root.val < q.val ) { - root = root.right - } else if (root.val > p.val && root.val > q.val) { - root = root.left - } else { - return root - } +var lowestCommonAncestor = function (root, p, q) { + while (root !== null) { + if (root.val < p.val && root.val < q.val) { + root = root.right; + } else if (root.val > p.val && root.val > q.val) { + root = root.left; + } else { + return root; } -}; \ No newline at end of file + } +}; diff --git a/javascript/238-Product-of-Array-Except-Self.js b/javascript/238-Product-of-Array-Except-Self.js index 819d9075b..63baebaef 100644 --- a/javascript/238-Product-of-Array-Except-Self.js +++ b/javascript/238-Product-of-Array-Except-Self.js @@ -2,21 +2,20 @@ * @param {number[]} nums * @return {number[]} */ -var productExceptSelf = function(nums) { - const res = []; - - let product = 1; - - for (let i = 0; i < nums.length; i++) { - res[i] = product; - product *= nums[i]; - } - product = 1; - for (let j = nums.length - 1; j >= 0; j--) { - res[j] *= product; - product *= nums[j]; - } - - return res; - +var productExceptSelf = function (nums) { + const res = []; + + let product = 1; + + for (let i = 0; i < nums.length; i++) { + res[i] = product; + product *= nums[i]; + } + product = 1; + for (let j = nums.length - 1; j >= 0; j--) { + res[j] *= product; + product *= nums[j]; + } + + return res; }; diff --git a/javascript/239-Sliding-Window-Maximum.js b/javascript/239-Sliding-Window-Maximum.js index 263022d39..6ac0ea364 100644 --- a/javascript/239-Sliding-Window-Maximum.js +++ b/javascript/239-Sliding-Window-Maximum.js @@ -3,17 +3,17 @@ * @param {number} k * @return {number[]} */ - function Node(value) { +function Node(value) { this.value = value; this.prev = null; this.next = null; -}; +} function Deque() { this.left = null; this.right = null; this.size = 0; - this.pushRight = function(value) { + this.pushRight = function (value) { const node = new Node(value); if (this.size == 0) { this.left = node; @@ -26,7 +26,7 @@ function Deque() { this.size++; return this.size; }; - this.popRight = function() { + this.popRight = function () { if (this.size == 0) return null; const removedNode = this.right; this.right = this.right.prev; @@ -34,7 +34,7 @@ function Deque() { this.size--; return removedNode; }; - this.pushLeft = function(value) { + this.pushLeft = function (value) { const node = new Node(value); if (this.size == 0) { this.left = node; @@ -47,7 +47,7 @@ function Deque() { this.size++; return this.size; }; - this.popLeft = function() { + this.popLeft = function () { if (this.size == 0) return null; const removedNode = this.left; this.left = this.left.next; @@ -55,27 +55,28 @@ function Deque() { this.size--; return removedNode; }; -}; +} -var maxSlidingWindow = function(nums, k) { - const output = []; - let deque = new Deque(); +var maxSlidingWindow = function (nums, k) { + const output = []; + let deque = new Deque(); let left = 0; let right = 0; - + while (right < nums.length) { // pop smaller values from q - while (deque.right && nums[deque.right.value] < nums[right]) deque.popRight(); + while (deque.right && nums[deque.right.value] < nums[right]) + deque.popRight(); deque.pushRight(right); - + // remove left val from window if (left > deque.left.value) deque.popLeft(); - - if (right +1 >= k) { + + if (right + 1 >= k) { output.push(nums[deque.left.value]); left++; - }; + } right++; - }; - return output; -}; \ No newline at end of file + } + return output; +}; diff --git a/javascript/242-Valid-Anagram.js b/javascript/242-Valid-Anagram.js index 92945fdb6..3b7f07e84 100644 --- a/javascript/242-Valid-Anagram.js +++ b/javascript/242-Valid-Anagram.js @@ -3,28 +3,28 @@ * @param {string} t * @return {boolean} */ -var isAnagram = function(s, t) { - if(s.length !== t.length) { - return false; +var isAnagram = function (s, t) { + if (s.length !== t.length) { + return false; + } + let sMap = {}; + let tMap = {}; + for (let i = 0; i < s.length; i++) { + if (sMap.hasOwnProperty(s[i])) { + sMap[s[i]]++; + } else { + sMap[s[i]] = 1; } - let sMap = {}; - let tMap = {}; - for(let i = 0; i < s.length; i++) { - if(sMap.hasOwnProperty(s[i])) { - sMap[s[i]]++ - } else { - sMap[s[i]] = 1; - } - if(tMap.hasOwnProperty(t[i])) { - tMap[t[i]]++ - } else { - tMap[t[i]] = 1; - } + if (tMap.hasOwnProperty(t[i])) { + tMap[t[i]]++; + } else { + tMap[t[i]] = 1; } - for(let k in sMap) { - if(sMap[k] !== tMap[k]) { - return false; - } + } + for (let k in sMap) { + if (sMap[k] !== tMap[k]) { + return false; } - return true; + } + return true; }; diff --git a/javascript/25-Reverse-Nodes-in-K-Group.js b/javascript/25-Reverse-Nodes-in-K-Group.js index 6b99b3815..5d73a791b 100644 --- a/javascript/25-Reverse-Nodes-in-K-Group.js +++ b/javascript/25-Reverse-Nodes-in-K-Group.js @@ -1,51 +1,51 @@ -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @param {number} k - * @return {ListNode} - */ -var reverseKGroup = function(head, k) { - let dummy = new ListNode(0, head); - let groupPrev = dummy; - - while (true) { - let kth = getKth(groupPrev, k); - if (!kth) { - break; - } - - let groupNext = kth.next; - - // reverse group - let prev = kth.next; - let curr = groupPrev.next; - - while (curr !== groupNext) { - let temp = curr.next; - curr.next = prev; - prev = curr; - curr = temp; - } - - let temp = groupPrev.next; - groupPrev.next = kth; - groupPrev = temp; - } - - return dummy.next; -}; - -function getKth(curr, k) { - while (curr && k > 0) { - curr = curr.next; - k -= 1; - } - - return curr; -} \ No newline at end of file +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} k + * @return {ListNode} + */ +var reverseKGroup = function (head, k) { + let dummy = new ListNode(0, head); + let groupPrev = dummy; + + while (true) { + let kth = getKth(groupPrev, k); + if (!kth) { + break; + } + + let groupNext = kth.next; + + // reverse group + let prev = kth.next; + let curr = groupPrev.next; + + while (curr !== groupNext) { + let temp = curr.next; + curr.next = prev; + prev = curr; + curr = temp; + } + + let temp = groupPrev.next; + groupPrev.next = kth; + groupPrev = temp; + } + + return dummy.next; +}; + +function getKth(curr, k) { + while (curr && k > 0) { + curr = curr.next; + k -= 1; + } + + return curr; +} diff --git a/javascript/268-Missing-Number.js b/javascript/268-Missing-Number.js index 0c9b10b25..ead5bebe9 100644 --- a/javascript/268-Missing-Number.js +++ b/javascript/268-Missing-Number.js @@ -1,19 +1,19 @@ var missingNumberWithSums = function (nums) { - let res = nums.length; + let res = nums.length; - for(let i = 0; i < nums.length; i++) { - res += i - nums[i]; - } + for (let i = 0; i < nums.length; i++) { + res += i - nums[i]; + } - return res; + return res; }; var missingNumberWithBit = function (nums) { - let res = nums.length; + let res = nums.length; - for(let i = 0; i < nums.length; i++) { - res = res ^ i ^ nums[i]; - } + for (let i = 0; i < nums.length; i++) { + res = res ^ i ^ nums[i]; + } - return res; + return res; }; diff --git a/javascript/269-Alien-Dictionary.js b/javascript/269-Alien-Dictionary.js index acf7242e3..0a3c9af6a 100644 --- a/javascript/269-Alien-Dictionary.js +++ b/javascript/269-Alien-Dictionary.js @@ -1,55 +1,55 @@ let alienOrder = function (words) { - let graph = {}; + let graph = {}; - for (let i = 0; i < words.length; i++) { - for (let j = 0; j < words[i].length; j++) { - graph[words[i][j]] = new Set(); - } + for (let i = 0; i < words.length; i++) { + for (let j = 0; j < words[i].length; j++) { + graph[words[i][j]] = new Set(); } + } - for (let i = 0; i < words.length - 1; i++) { - let word1 = words[i]; - let word2 = words[i + 1]; + for (let i = 0; i < words.length - 1; i++) { + let word1 = words[i]; + let word2 = words[i + 1]; - if (word1.length > word2.length && (word1 + '').startsWith(word2)) { - return ""; - } + if (word1.length > word2.length && (word1 + '').startsWith(word2)) { + return ''; + } - for (let j = 0; j < Math.min(word1.length, word2.length); j++) { - let c1 = word1[j]; - let c2 = word2[j]; + for (let j = 0; j < Math.min(word1.length, word2.length); j++) { + let c1 = word1[j]; + let c2 = word2[j]; - if (c1 !== c2) { - graph[c1].add(c2); - break; - } - } + if (c1 !== c2) { + graph[c1].add(c2); + break; + } } + } - let visited = {}; // 'false' = visited, 'true' = current path - let res = []; - - function dfs(c) { - if (visited[c]) { - return Boolean(visited[c]); - } + let visited = {}; // 'false' = visited, 'true' = current path + let res = []; - visited[c] = 'true'; - for (let nei of graph[c]) { - if (dfs(nei)) { - return true; - } - } + function dfs(c) { + if (visited[c]) { + return Boolean(visited[c]); + } - visited[c] = 'false'; - res.push(c); + visited[c] = 'true'; + for (let nei of graph[c]) { + if (dfs(nei)) { + return true; + } } - Object.keys(graph).forEach(c => { - if (dfs(c)) { - return ''; - } - }) + visited[c] = 'false'; + res.push(c); + } + + Object.keys(graph).forEach((c) => { + if (dfs(c)) { + return ''; + } + }); - return res.reverse().join(''); -} + return res.reverse().join(''); +}; diff --git a/javascript/271-Encode-and-Decode-Strings.js b/javascript/271-Encode-and-Decode-Strings.js index 5ea7a6d29..2470ba893 100644 --- a/javascript/271-Encode-and-Decode-Strings.js +++ b/javascript/271-Encode-and-Decode-Strings.js @@ -3,7 +3,7 @@ * @return {string} */ function encode(strs) { - return strs.map(str => `${str.length}#${str}`).join(''); + return strs.map((str) => `${str.length}#${str}`).join(''); } /** @@ -11,20 +11,19 @@ function encode(strs) { * @return {string[]} */ function decode(str) { - const res = []; - let i = 0; + const res = []; + let i = 0; - while (i < str.length) { - let j = i; - while (str[j] !== "#") { - ++j; - } - - const len = Number(str.slice(i, j)); - res.push(str.slice(++j, j + len)); - i = j + len; + while (i < str.length) { + let j = i; + while (str[j] !== '#') { + ++j; } - return res; -} + const len = Number(str.slice(i, j)); + res.push(str.slice(++j, j + len)); + i = j + len; + } + return res; +} diff --git a/javascript/286-Walls-And-Gates.js b/javascript/286-Walls-And-Gates.js index 69f7c4c14..b15e65d17 100644 --- a/javascript/286-Walls-And-Gates.js +++ b/javascript/286-Walls-And-Gates.js @@ -15,16 +15,16 @@ const INF = 2 ** 31 - 1; * @return {void} Do not return anything, modify rooms in-place instead. */ function wallsAndGates(rooms) { - for (let i = 0; i < rooms.length; ++i) { - for (let j = 0; j < rooms[0].length; ++j) { - if (rooms[i][j] === 0) { - fillRooms(rooms, i - 1, j); - fillRooms(rooms, i + 1, j); - fillRooms(rooms, i, j - 1); - fillRooms(rooms, i, j + 1); - } - } + for (let i = 0; i < rooms.length; ++i) { + for (let j = 0; j < rooms[0].length; ++j) { + if (rooms[i][j] === 0) { + fillRooms(rooms, i - 1, j); + fillRooms(rooms, i + 1, j); + fillRooms(rooms, i, j - 1); + fillRooms(rooms, i, j + 1); + } } + } } /** @@ -35,23 +35,22 @@ function wallsAndGates(rooms) { * @return {void} */ function fillRooms(rooms, i, j, count = 0) { - - if (!inBounds(rooms, i, j) || rooms[i][j] < 1) { - return; - } - - ++count; - - if (rooms[i][j] !== INF && rooms[i][j] <= count) { - return; - } - - rooms[i][j] = count; - - fillRooms(rooms, i - 1, j, count); - fillRooms(rooms, i + 1, j, count); - fillRooms(rooms, i, j - 1, count); - fillRooms(rooms, i, j + 1, count); + if (!inBounds(rooms, i, j) || rooms[i][j] < 1) { + return; + } + + ++count; + + if (rooms[i][j] !== INF && rooms[i][j] <= count) { + return; + } + + rooms[i][j] = count; + + fillRooms(rooms, i - 1, j, count); + fillRooms(rooms, i + 1, j, count); + fillRooms(rooms, i, j - 1, count); + fillRooms(rooms, i, j + 1, count); } /** @@ -61,7 +60,7 @@ function fillRooms(rooms, i, j, count = 0) { * @return {boolean} */ function inBounds(rooms, i, j) { - return i >= 0 && j >= 0 && i < rooms.length && j < rooms[0].length; + return i >= 0 && j >= 0 && i < rooms.length && j < rooms[0].length; } ////////////////////////////////////////////////////////////////////////////// @@ -76,10 +75,10 @@ function inBounds(rooms, i, j) { const INF = 2 ** 31 - 1; const DIRECTIONS = [ - [ -1, 0 ], - [ 1, 0 ], - [ 0, -1 ], - [ 0, 1 ], + [-1, 0], + [1, 0], + [0, -1], + [0, 1], ]; /** @@ -87,39 +86,36 @@ const DIRECTIONS = [ * @return {void} */ function wallsAndGates(rooms) { - - const queue = []; - - for (let i = 0; i < rooms.length; ++i) { - for (let j = 0; j < rooms[0].length; ++j) { - if (rooms[i][j] === 0) { - queue.push([ i, j ]); - } - } + const queue = []; + + for (let i = 0; i < rooms.length; ++i) { + for (let j = 0; j < rooms[0].length; ++j) { + if (rooms[i][j] === 0) { + queue.push([i, j]); + } } - - let count = 1; - - while (queue.length) { - - let length = queue.length; - - while (length--) { - - [ i, j ] = queue.shift(); - - for ([ k, l ] of DIRECTIONS) { - k += i; - l += j; - if (inBounds(rooms, k, l) && rooms[k][l] === INF) { - rooms[k][l] = count; - queue.push([ k, l ]); - } - } + } + + let count = 1; + + while (queue.length) { + let length = queue.length; + + while (length--) { + [i, j] = queue.shift(); + + for ([k, l] of DIRECTIONS) { + k += i; + l += j; + if (inBounds(rooms, k, l) && rooms[k][l] === INF) { + rooms[k][l] = count; + queue.push([k, l]); } - - ++count; + } } + + ++count; + } } /** @@ -129,5 +125,5 @@ function wallsAndGates(rooms) { * @return {boolean} */ function inBounds(rooms, i, j) { - return i >= 0 && j >= 0 && i < rooms.length && j < rooms[0].length; -} \ No newline at end of file + return i >= 0 && j >= 0 && i < rooms.length && j < rooms[0].length; +} diff --git a/javascript/287-Find-the-Duplicate-Number.js b/javascript/287-Find-the-Duplicate-Number.js index 8f0e9dbd0..83627c687 100644 --- a/javascript/287-Find-the-Duplicate-Number.js +++ b/javascript/287-Find-the-Duplicate-Number.js @@ -1,24 +1,24 @@ -function findDuplicate(nums) { - let slow = 0; - let fast = 0; - - while (true) { - slow = nums[slow]; - fast = nums[nums[fast]]; - if (slow == fast) { - break; - } - } - - let slow2 = 0; - - while (true) { - slow = nums[slow]; - slow2 = nums[slow2]; - if (slow == slow2) { - break; - } - } - - return slow; -} +function findDuplicate(nums) { + let slow = 0; + let fast = 0; + + while (true) { + slow = nums[slow]; + fast = nums[nums[fast]]; + if (slow == fast) { + break; + } + } + + let slow2 = 0; + + while (true) { + slow = nums[slow]; + slow2 = nums[slow2]; + if (slow == slow2) { + break; + } + } + + return slow; +} diff --git a/javascript/297-Serialize-and-Deserialize-Binary-Tree.js b/javascript/297-Serialize-and-Deserialize-Binary-Tree.js index 11f973b87..75b4cd2c2 100644 --- a/javascript/297-Serialize-and-Deserialize-Binary-Tree.js +++ b/javascript/297-Serialize-and-Deserialize-Binary-Tree.js @@ -1,62 +1,62 @@ -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ - -/** - * Encodes a tree to a single string. - * - * @param {TreeNode} root - * @return {string} - */ -var serialize = function(root) { - const res = []; - - function dfs(node) { - if (!node) { - res.push("N") - return; - } - - res.push(String(node.val)); - dfs(node.left); - dfs(node.right); - } - - dfs(root); - return res.join(","); -}; - -/** - * Decodes your encoded data to tree. - * - * @param {string} data - * @return {TreeNode} - */ -var deserialize = function(data) { - const vals = data.split(","); - let i = 0; - - function dfs() { - if (vals[i] === "N") { - i++; - return null; - } - - const node = new TreeNode(parseInt(vals[i])); - i++; - node.left = dfs(); - node.right = dfs(); - return node; - } - - return dfs(); -}; - -/** - * Your functions will be called as such: - * deserialize(serialize(root)); - */ \ No newline at end of file +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ + +/** + * Encodes a tree to a single string. + * + * @param {TreeNode} root + * @return {string} + */ +var serialize = function (root) { + const res = []; + + function dfs(node) { + if (!node) { + res.push('N'); + return; + } + + res.push(String(node.val)); + dfs(node.left); + dfs(node.right); + } + + dfs(root); + return res.join(','); +}; + +/** + * Decodes your encoded data to tree. + * + * @param {string} data + * @return {TreeNode} + */ +var deserialize = function (data) { + const vals = data.split(','); + let i = 0; + + function dfs() { + if (vals[i] === 'N') { + i++; + return null; + } + + const node = new TreeNode(parseInt(vals[i])); + i++; + node.left = dfs(); + node.right = dfs(); + return node; + } + + return dfs(); +}; + +/** + * Your functions will be called as such: + * deserialize(serialize(root)); + */ diff --git a/javascript/3-Longest-Substring-Without-Repeating-Characters.js b/javascript/3-Longest-Substring-Without-Repeating-Characters.js index 6969dd390..7506b5319 100644 --- a/javascript/3-Longest-Substring-Without-Repeating-Characters.js +++ b/javascript/3-Longest-Substring-Without-Repeating-Characters.js @@ -19,4 +19,4 @@ var lengthOfLongestSubstring = function (str) { max = Math.max(max, i - start + 1); } return max; -}; \ No newline at end of file +}; diff --git a/javascript/300-Longest-Increasing-Subsequence.js b/javascript/300-Longest-Increasing-Subsequence.js index d7b63b06c..e223335e9 100644 --- a/javascript/300-Longest-Increasing-Subsequence.js +++ b/javascript/300-Longest-Increasing-Subsequence.js @@ -1,12 +1,12 @@ -var lengthOfLIS = function(nums) { - let arr = Array(nums.length).fill(1); - - for(let i = 1; i < arr.length; i++) { - for (let j = 0; j < i; j++) { - if (nums[i] > nums[j]) { - arr[i] = Math.max(arr[i], arr[j] + 1); - } - } +var lengthOfLIS = function (nums) { + let arr = Array(nums.length).fill(1); + + for (let i = 1; i < arr.length; i++) { + for (let j = 0; j < i; j++) { + if (nums[i] > nums[j]) { + arr[i] = Math.max(arr[i], arr[j] + 1); + } } - return Math.max(...arr); + } + return Math.max(...arr); }; diff --git a/javascript/322-Coin-Change.js b/javascript/322-Coin-Change.js index 165a8408b..b25f64913 100644 --- a/javascript/322-Coin-Change.js +++ b/javascript/322-Coin-Change.js @@ -3,15 +3,15 @@ * @param {number} amount * @return {number} */ -var coinChange = function(coins, amount) { - let dp = Array(amount+1).fill(amount+1) - dp[0]=0 - for(let i=1; i= 0) { - dp[i] = Math.min(dp[i], 1 + dp[i-coin]) - } - } +var coinChange = function (coins, amount) { + let dp = Array(amount + 1).fill(amount + 1); + dp[0] = 0; + for (let i = 1; i < dp.length; i++) { + for (const coin of coins) { + if (i - coin >= 0) { + dp[i] = Math.min(dp[i], 1 + dp[i - coin]); + } } - return dp[amount] === amount+1 ? -1 : dp.pop() + } + return dp[amount] === amount + 1 ? -1 : dp.pop(); }; diff --git a/javascript/323-countComponents.js b/javascript/323-countComponents.js index f22972ebd..76a83f273 100644 --- a/javascript/323-countComponents.js +++ b/javascript/323-countComponents.js @@ -35,4 +35,4 @@ var countComponents = function (n, edges) { } } return count; -}; \ No newline at end of file +}; diff --git a/javascript/33-Search-in-Rotated-Sorted-Array.js b/javascript/33-Search-in-Rotated-Sorted-Array.js index 97d83dcc9..a5af31b96 100644 --- a/javascript/33-Search-in-Rotated-Sorted-Array.js +++ b/javascript/33-Search-in-Rotated-Sorted-Array.js @@ -3,42 +3,39 @@ * @param {number} target * @return {number} */ -var search = function(nums, target) { +var search = function (nums, target) { let left = 0; let right = nums.length - 1; - + while (left <= right) { let mid = Math.floor((left + right) / 2); - + if (nums[mid] === target) { return mid; } - + // Checking if the left side is sorted if (nums[left] <= nums[mid]) { if (nums[left] <= target && target <= nums[mid]) { // thus target is in the left right = mid - 1; - } else { // thus target is in the right left = mid + 1; } - } - + } + // Otherwise, the right side is sorted else { if (nums[mid] <= target && target <= nums[right]) { // thus target is in the right left = mid + 1; - } else { // thus target is in the left right = mid - 1; } } - } - + return -1; }; diff --git a/javascript/332-Reconstruct-Itinerary.js b/javascript/332-Reconstruct-Itinerary.js index dd9a3ffe7..8c3e450c8 100644 --- a/javascript/332-Reconstruct-Itinerary.js +++ b/javascript/332-Reconstruct-Itinerary.js @@ -3,42 +3,42 @@ * @return {string[]} */ var findItinerary = function (tickets) { - const flight_paths = new Map(); - const flight_path_order = ["JFK"]; + const flight_paths = new Map(); + const flight_path_order = ['JFK']; - tickets = tickets.sort(); + tickets = tickets.sort(); - for (const [source, dest] of tickets) { - let edges = []; - if (flight_paths.has(source)) { - edges = flight_paths.get(source); - } - edges.push(dest); - flight_paths.set(source, edges); - } + for (const [source, dest] of tickets) { + let edges = []; + if (flight_paths.has(source)) { + edges = flight_paths.get(source); + } + edges.push(dest); + flight_paths.set(source, edges); + } - const depth_first_search = (city) => { - if (flight_path_order.length === tickets.length + 1) return true; + const depth_first_search = (city) => { + if (flight_path_order.length === tickets.length + 1) return true; - const cities_to_go_to = flight_paths.get(city) || []; - if (!cities_to_go_to.length) return false; + const cities_to_go_to = flight_paths.get(city) || []; + if (!cities_to_go_to.length) return false; - const cities_copied = Array.from(cities_to_go_to); + const cities_copied = Array.from(cities_to_go_to); - for (const other_city of cities_copied) { - flight_path_order.push(other_city); - cities_to_go_to.shift(); + for (const other_city of cities_copied) { + flight_path_order.push(other_city); + cities_to_go_to.shift(); - if (depth_first_search(other_city)) { - return flight_path_order; - } else { - flight_path_order.pop(); - cities_to_go_to.push(other_city); - } - } + if (depth_first_search(other_city)) { + return flight_path_order; + } else { + flight_path_order.pop(); + cities_to_go_to.push(other_city); + } + } - return false; - }; + return false; + }; - return depth_first_search("JFK"); + return depth_first_search('JFK'); }; diff --git a/javascript/338-Counting-Bits.js b/javascript/338-Counting-Bits.js index f6251cd34..e5685401d 100644 --- a/javascript/338-Counting-Bits.js +++ b/javascript/338-Counting-Bits.js @@ -3,9 +3,9 @@ * @return {number[]} */ var countBits = function (n) { - let output = [0]; - for (let i = 1; i < n + 1; i++) { - output.push((output[i >> 1] + (i & 1))); - } - return output; + let output = [0]; + for (let i = 1; i < n + 1; i++) { + output.push(output[i >> 1] + (i & 1)); + } + return output; }; diff --git a/javascript/347-Top-K-Frequent-Elements.js b/javascript/347-Top-K-Frequent-Elements.js index 988245061..3b6a5e8da 100644 --- a/javascript/347-Top-K-Frequent-Elements.js +++ b/javascript/347-Top-K-Frequent-Elements.js @@ -3,29 +3,28 @@ * @param {number} k * @return {number[]} */ -var topKFrequent = function(nums, k) { - let map = new Map(); - let res = []; - let bucket = Array.from({ length: nums.length + 1 }, () => []); // to create unique arrays - - // storing frequency of numbers in a map - for (let n of nums) { - map.set(n, (map.has(n) ? 1 + map.get(n) : 1)) - } +var topKFrequent = function (nums, k) { + let map = new Map(); + let res = []; + let bucket = Array.from({ length: nums.length + 1 }, () => []); // to create unique arrays - // Poppulate the bucket with numbers in frequency - // as the index of the bucket - for (const [key, value] of map.entries()) { - bucket[value].push(key); - } - - for (let i = bucket.length - 1; i >= 0; i--) { - if (bucket[i].length > 0) { - for (let n of bucket[i]) { - res.push(n); - if (res.length === k) - return res; - } - } + // storing frequency of numbers in a map + for (let n of nums) { + map.set(n, map.has(n) ? 1 + map.get(n) : 1); + } + + // Poppulate the bucket with numbers in frequency + // as the index of the bucket + for (const [key, value] of map.entries()) { + bucket[value].push(key); + } + + for (let i = bucket.length - 1; i >= 0; i--) { + if (bucket[i].length > 0) { + for (let n of bucket[i]) { + res.push(n); + if (res.length === k) return res; + } } + } }; diff --git a/javascript/347-Top-K-Frquent-Elements.js b/javascript/347-Top-K-Frquent-Elements.js index 988245061..3b6a5e8da 100644 --- a/javascript/347-Top-K-Frquent-Elements.js +++ b/javascript/347-Top-K-Frquent-Elements.js @@ -3,29 +3,28 @@ * @param {number} k * @return {number[]} */ -var topKFrequent = function(nums, k) { - let map = new Map(); - let res = []; - let bucket = Array.from({ length: nums.length + 1 }, () => []); // to create unique arrays - - // storing frequency of numbers in a map - for (let n of nums) { - map.set(n, (map.has(n) ? 1 + map.get(n) : 1)) - } +var topKFrequent = function (nums, k) { + let map = new Map(); + let res = []; + let bucket = Array.from({ length: nums.length + 1 }, () => []); // to create unique arrays - // Poppulate the bucket with numbers in frequency - // as the index of the bucket - for (const [key, value] of map.entries()) { - bucket[value].push(key); - } - - for (let i = bucket.length - 1; i >= 0; i--) { - if (bucket[i].length > 0) { - for (let n of bucket[i]) { - res.push(n); - if (res.length === k) - return res; - } - } + // storing frequency of numbers in a map + for (let n of nums) { + map.set(n, map.has(n) ? 1 + map.get(n) : 1); + } + + // Poppulate the bucket with numbers in frequency + // as the index of the bucket + for (const [key, value] of map.entries()) { + bucket[value].push(key); + } + + for (let i = bucket.length - 1; i >= 0; i--) { + if (bucket[i].length > 0) { + for (let n of bucket[i]) { + res.push(n); + if (res.length === k) return res; + } } + } }; diff --git a/javascript/35-Search-Insert-Position.js b/javascript/35-Search-Insert-Position.js index cb4f1e72c..c4ce6ff93 100644 --- a/javascript/35-Search-Insert-Position.js +++ b/javascript/35-Search-Insert-Position.js @@ -3,21 +3,21 @@ * @param {number} target * @return {number} */ -var searchInsert = function(nums, target) { - let left = 0; - let right = nums.length - 1; - while (left <= right) { - let midIdx = Math.floor((left + right) / 2); - if (target === nums[midIdx]) { - return midIdx; - } +var searchInsert = function (nums, target) { + let left = 0; + let right = nums.length - 1; + while (left <= right) { + let midIdx = Math.floor((left + right) / 2); + if (target === nums[midIdx]) { + return midIdx; + } - if (target > nums[midIdx]) { - left = midIdx + 1; - } else { - right = midIdx - 1; - } + if (target > nums[midIdx]) { + left = midIdx + 1; + } else { + right = midIdx - 1; } - - return left; + } + + return left; }; diff --git a/javascript/36-Valid-Sudoku.js b/javascript/36-Valid-Sudoku.js index fdd59b41a..570930a72 100644 --- a/javascript/36-Valid-Sudoku.js +++ b/javascript/36-Valid-Sudoku.js @@ -3,39 +3,39 @@ * @return {boolean} */ function isValidSudoku(board) { - const rows = {}; - const cols = {}; - const squares = {}; + const rows = {}; + const cols = {}; + const squares = {}; - for (let r = 0; r < 9; r++) { - for (let c = 0; c < 9; c++) { - const num = board[r][c]; + for (let r = 0; r < 9; r++) { + for (let c = 0; c < 9; c++) { + const num = board[r][c]; - if (num === '.') { - continue; - } + if (num === '.') { + continue; + } - const grid = `${Math.floor(r / 3)}${Math.floor(c / 3)}`; + const grid = `${Math.floor(r / 3)}${Math.floor(c / 3)}`; - if (!cols[c]) { - cols[c] = new Set(); - } - if (!rows[r]) { - rows[r] = new Set(); - } - if (!squares[grid]) { - squares[grid] = new Set(); - } + if (!cols[c]) { + cols[c] = new Set(); + } + if (!rows[r]) { + rows[r] = new Set(); + } + if (!squares[grid]) { + squares[grid] = new Set(); + } - if (rows[r].has(num) || cols[c].has(num) || squares[grid].has(num)) { - return false; - } + if (rows[r].has(num) || cols[c].has(num) || squares[grid].has(num)) { + return false; + } - cols[c].add(num) - rows[r].add(num) - squares[grid].add(num) - } + cols[c].add(num); + rows[r].add(num); + squares[grid].add(num); } + } - return true; + return true; } diff --git a/javascript/371-Sum-of-Two-Integers.js b/javascript/371-Sum-of-Two-Integers.js index 8f4c16c53..ca0976262 100644 --- a/javascript/371-Sum-of-Two-Integers.js +++ b/javascript/371-Sum-of-Two-Integers.js @@ -1,12 +1,12 @@ -var getSum = function(a, b) { - let tb = b; - let res = a; +var getSum = function (a, b) { + let tb = b; + let res = a; - while(tb) { - let temp = (res & tb) << 1; - res = res ^ tb; - tb = temp; - } + while (tb) { + let temp = (res & tb) << 1; + res = res ^ tb; + tb = temp; + } - return res; + return res; }; diff --git a/javascript/39-Combination-Sum.js b/javascript/39-Combination-Sum.js index c9d46b94b..381f8932b 100644 --- a/javascript/39-Combination-Sum.js +++ b/javascript/39-Combination-Sum.js @@ -10,33 +10,31 @@ * @return {number[][]} */ function combinationSum(candidates, target) { - - candidates.sort((a, b) => a - b); - const combos = []; - const combo = []; - const set = new Set(candidates); - buildCombos(target); - return combos; - - /** - * @param {number} target - * @param {number=} start = `0` - * @return {void} - */ - function buildCombos(target, start = 0) { - - if (set.has(target)) { - combo.push(target); - combos.push(combo.slice()); - combo.pop(); - } - - const mid = Math.floor(target / 2); - for (let i = start; i < candidates.length && candidates[i] <= mid; ++i) { - const candidate = candidates[i]; - combo.push(candidate); - buildCombos(target - candidate, i); - combo.pop(); - } + candidates.sort((a, b) => a - b); + const combos = []; + const combo = []; + const set = new Set(candidates); + buildCombos(target); + return combos; + + /** + * @param {number} target + * @param {number=} start = `0` + * @return {void} + */ + function buildCombos(target, start = 0) { + if (set.has(target)) { + combo.push(target); + combos.push(combo.slice()); + combo.pop(); + } + + const mid = Math.floor(target / 2); + for (let i = start; i < candidates.length && candidates[i] <= mid; ++i) { + const candidate = candidates[i]; + combo.push(candidate); + buildCombos(target - candidate, i); + combo.pop(); } + } } diff --git a/javascript/4-Median-Of-Two-Sorted-Arrays.js b/javascript/4-Median-Of-Two-Sorted-Arrays.js index 1f364ac01..f5e013ab5 100644 --- a/javascript/4-Median-Of-Two-Sorted-Arrays.js +++ b/javascript/4-Median-Of-Two-Sorted-Arrays.js @@ -3,34 +3,32 @@ * @param {number[]} nums2 * @return {number} */ -var findMedianSortedArrays = function(nums1, nums2) { - let [A, B] = [nums1, nums2] - const total = nums1.length + nums2.length - const half = Math.floor(total / 2) - - if (B.length < A.length) { - [A, B] = [B, A] - } - - let [l, r] = [0, A.length -1] - while (true) { - const i = (l + r) - const j = half - i - 2 - - const Aleft = i >= 0 ? A[i] : -Infinity - const Aright = (i + 1) < A.length ? A[i + 1] : Infinity - const Bleft = j >= 0 ? B[j] : -Infinity - const Bright = (j + 1) < B.length ? B[j + 1] : Infinity - - if (Aleft <= Bright && Bleft <= Aright) { - if (total % 2) { - return Math.min(Aright, Bright) - } - - return (Math.max(Aleft, Bleft) + Math.min(Aright, Bright)) / 2 - } - else if (Aleft > Bright) r = i - 1 - else l = i + 1 - } -}; +var findMedianSortedArrays = function (nums1, nums2) { + let [A, B] = [nums1, nums2]; + const total = nums1.length + nums2.length; + const half = Math.floor(total / 2); + + if (B.length < A.length) { + [A, B] = [B, A]; + } + + let [l, r] = [0, A.length - 1]; + while (true) { + const i = l + r; + const j = half - i - 2; + const Aleft = i >= 0 ? A[i] : -Infinity; + const Aright = i + 1 < A.length ? A[i + 1] : Infinity; + const Bleft = j >= 0 ? B[j] : -Infinity; + const Bright = j + 1 < B.length ? B[j + 1] : Infinity; + + if (Aleft <= Bright && Bleft <= Aright) { + if (total % 2) { + return Math.min(Aright, Bright); + } + + return (Math.max(Aleft, Bleft) + Math.min(Aright, Bright)) / 2; + } else if (Aleft > Bright) r = i - 1; + else l = i + 1; + } +}; diff --git a/javascript/40-Combination-Sum-II.js b/javascript/40-Combination-Sum-II.js index 5bffa58af..ca541c911 100644 --- a/javascript/40-Combination-Sum-II.js +++ b/javascript/40-Combination-Sum-II.js @@ -10,41 +10,39 @@ * @return {number[][]} */ function combinationSum2(candidates, target) { - - candidates.sort((a, b) => a - b); - - const combos = []; - const combo = []; - const map = Object.create(null); - - for (let i = 0; i < candidates.length; ++i) { - map[candidates[i]] = i; + candidates.sort((a, b) => a - b); + + const combos = []; + const combo = []; + const map = Object.create(null); + + for (let i = 0; i < candidates.length; ++i) { + map[candidates[i]] = i; + } + + getCombos(target); + return combos; + + /** + * @param {number} target + * @param {number=} start = `0` + * @return {void} + */ + function getCombos(target, start = 0) { + if (target in map && start <= map[target]) { + combo.push(target); + combos.push(combo.slice()); + combo.pop(); } - - getCombos(target); - return combos; - - /** - * @param {number} target - * @param {number=} start = `0` - * @return {void} - */ - function getCombos(target, start = 0) { - - if (target in map && start <= map[target]) { - combo.push(target); - combos.push(combo.slice()); - combo.pop(); - } - - const mid = Math.floor(target / 2); - for (let i = start; i < candidates.length && candidates[i] <= mid; ++i) { - if (i !== start && candidates[i] === candidates[i - 1]) { - continue; - } - combo.push(candidates[i]); - getCombos(target - candidates[i], i + 1); - combo.pop(); - } + + const mid = Math.floor(target / 2); + for (let i = start; i < candidates.length && candidates[i] <= mid; ++i) { + if (i !== start && candidates[i] === candidates[i - 1]) { + continue; + } + combo.push(candidates[i]); + getCombos(target - candidates[i], i + 1); + combo.pop(); } -} \ No newline at end of file + } +} diff --git a/javascript/417-Pacific-Atlantic-Water-Flow.js b/javascript/417-Pacific-Atlantic-Water-Flow.js index 93c32637b..4c247acfb 100644 --- a/javascript/417-Pacific-Atlantic-Water-Flow.js +++ b/javascript/417-Pacific-Atlantic-Water-Flow.js @@ -11,10 +11,10 @@ ////////////////////////////////////////////////////////////////////////////// class Drains { - constructor(west = false, east = false) { - this.west = west; - this.east = east; - } + constructor(west = false, east = false) { + this.west = west; + this.east = east; + } } /** @@ -22,74 +22,73 @@ class Drains { * @return {number[][]} */ function pacificAtlantic(heights) { - - const rowLen = heights.length; - const colLen = heights[0].length; - const lastRow = rowLen - 1; - const lastCol = colLen - 1; - const drainage = new Array(rowLen); - const drainsBoth = []; - - for (let r = 0; r < rowLen; ++r) { - drainage[r] = new Array(colLen); - for (let c = 0; c < colLen; ++c) { - drainage[r][c] = new Drains(); - } - } - - for (let r = 0; r < rowLen; ++r) { - markDrainage(r, 0, true); - markDrainage(r, lastCol); - } + const rowLen = heights.length; + const colLen = heights[0].length; + const lastRow = rowLen - 1; + const lastCol = colLen - 1; + const drainage = new Array(rowLen); + const drainsBoth = []; + + for (let r = 0; r < rowLen; ++r) { + drainage[r] = new Array(colLen); for (let c = 0; c < colLen; ++c) { - markDrainage(0, c, true); - markDrainage(lastRow, c); + drainage[r][c] = new Drains(); } - - return drainsBoth; - - /** - * @param {number} r - * @param {number} c - * @param {boolean=} west = `false` - * @param {number=} prev = `-Infinity` - * @return {void} - */ - function markDrainage(r, c, west = false, prev = -Infinity) { - - if (!inBounds(r, c) - || heights[r][c] < prev - || (west && drainage[r][c].west) - || (!west && drainage[r][c].east) - ) { - return; - } - - const drains = drainage[r][c]; - const height = heights[r][c]; - - if (west) { - drains.west = true; - } else { - drains.east = true; - } - - if (drains.west && drains.east) { - drainsBoth.push([ r, c ]); - } - - markDrainage(r - 1, c, west, height); - markDrainage(r + 1, c, west, height); - markDrainage(r, c - 1, west, height); - markDrainage(r, c + 1, west, height); + } + + for (let r = 0; r < rowLen; ++r) { + markDrainage(r, 0, true); + markDrainage(r, lastCol); + } + for (let c = 0; c < colLen; ++c) { + markDrainage(0, c, true); + markDrainage(lastRow, c); + } + + return drainsBoth; + + /** + * @param {number} r + * @param {number} c + * @param {boolean=} west = `false` + * @param {number=} prev = `-Infinity` + * @return {void} + */ + function markDrainage(r, c, west = false, prev = -Infinity) { + if ( + !inBounds(r, c) || + heights[r][c] < prev || + (west && drainage[r][c].west) || + (!west && drainage[r][c].east) + ) { + return; } - - /** - * @param {number} r - * @param {number} c - * @return {boolean} - */ - function inBounds(r, c) { - return r >= 0 && c >= 0 && r < rowLen && c < colLen; + + const drains = drainage[r][c]; + const height = heights[r][c]; + + if (west) { + drains.west = true; + } else { + drains.east = true; + } + + if (drains.west && drains.east) { + drainsBoth.push([r, c]); } + + markDrainage(r - 1, c, west, height); + markDrainage(r + 1, c, west, height); + markDrainage(r, c - 1, west, height); + markDrainage(r, c + 1, west, height); + } + + /** + * @param {number} r + * @param {number} c + * @return {boolean} + */ + function inBounds(r, c) { + return r >= 0 && c >= 0 && r < rowLen && c < colLen; + } } diff --git a/javascript/42-Trapping-Rain-Water.js b/javascript/42-Trapping-Rain-Water.js index 1eac50b46..10adc430d 100644 --- a/javascript/42-Trapping-Rain-Water.js +++ b/javascript/42-Trapping-Rain-Water.js @@ -7,32 +7,31 @@ * @return {number} */ function trap(heights) { - - let l = 0; - let r = heights.length - 1; - let lMax = 0; - let rMax = 0; - let total = 0; - - while (l < r) { - if (heights[l] < heights[r]) { - if (heights[l] >= lMax) { - lMax = heights[l]; - } else { - total += lMax - heights[l]; - } - ++l; - } else { - if (heights[r] >= rMax) { - rMax = heights[r]; - } else { - total += rMax - heights[r]; - } - --r; - } + let l = 0; + let r = heights.length - 1; + let lMax = 0; + let rMax = 0; + let total = 0; + + while (l < r) { + if (heights[l] < heights[r]) { + if (heights[l] >= lMax) { + lMax = heights[l]; + } else { + total += lMax - heights[l]; + } + ++l; + } else { + if (heights[r] >= rMax) { + rMax = heights[r]; + } else { + total += rMax - heights[r]; + } + --r; } - - return total; + } + + return total; } ////////////////////////////////////////////////////////////////////////////// @@ -44,29 +43,27 @@ function trap(heights) { * @return {number} */ function trap(heights) { - - const stack = []; - let total = 0; - - for (let i = 0; i < heights.length; ++i) { - while (stack.length && heights[i] > heights[top(stack)]) { - - const j = stack.pop(); - - if (!stack.length) { - break; - } - - const k = top(stack); - const spread = i - k - 1; - const height = Math.min(heights[i], heights[k]) - heights[j]; - total += spread * height; - } - - stack.push(i); + const stack = []; + let total = 0; + + for (let i = 0; i < heights.length; ++i) { + while (stack.length && heights[i] > heights[top(stack)]) { + const j = stack.pop(); + + if (!stack.length) { + break; + } + + const k = top(stack); + const spread = i - k - 1; + const height = Math.min(heights[i], heights[k]) - heights[j]; + total += spread * height; } - - return total; + + stack.push(i); + } + + return total; } /** @@ -74,7 +71,7 @@ function trap(heights) { * @return {*} */ function top(stack) { - return stack[stack.length - 1]; + return stack[stack.length - 1]; } ////////////////////////////////////////////////////////////////////////////// @@ -86,38 +83,37 @@ function top(stack) { * @return {number} */ function trap(heights) { - - let valley = []; - let barrier = 0; - let trapped = 0; - - for (const height of heights) { - if (height >= barrier) { - while (valley.length) { - trapped += barrier - valley.pop(); - } - barrier = height; - } else { - valley.push(height); - } + let valley = []; + let barrier = 0; + let trapped = 0; + + for (const height of heights) { + if (height >= barrier) { + while (valley.length) { + trapped += barrier - valley.pop(); + } + barrier = height; + } else { + valley.push(height); } - - valley.reverse(); - valley.push(barrier); - heights = valley; - valley = []; - barrier = 0; - - for (const height of heights) { - if (height >= barrier) { - while (valley.length) { - trapped += barrier - valley.pop(); - } - barrier = height; - } else { - valley.push(height); - } + } + + valley.reverse(); + valley.push(barrier); + heights = valley; + valley = []; + barrier = 0; + + for (const height of heights) { + if (height >= barrier) { + while (valley.length) { + trapped += barrier - valley.pop(); + } + barrier = height; + } else { + valley.push(height); } - - return trapped; + } + + return trapped; } diff --git a/javascript/424-Longest-Repeating-Character-Replacement.js b/javascript/424-Longest-Repeating-Character-Replacement.js index cfc33f945..9f51c627b 100644 --- a/javascript/424-Longest-Repeating-Character-Replacement.js +++ b/javascript/424-Longest-Repeating-Character-Replacement.js @@ -3,29 +3,28 @@ * @param {number} k * @return {number} */ - var characterReplacement = function(s, k) { - let sCharacterSet = {}; - let result = 0; - let l = 0; - let maxLength = 0; - - for(let r = 0; r < s.length; r++){ - if(sCharacterSet[s[r]] !== undefined){ - sCharacterSet[s[r]] = 1 + sCharacterSet[s[r]]; - } else { - sCharacterSet[s[r]] = 1; - } - - maxLength = Math.max(maxLength, sCharacterSet[s[r]]) - - if ((r - l + 1) - maxLength > k){ - sCharacterSet[s[l]] -= 1; - l += 1; - } - - result = Math.max(result, r - l + 1); +var characterReplacement = function (s, k) { + let sCharacterSet = {}; + let result = 0; + let l = 0; + let maxLength = 0; + + for (let r = 0; r < s.length; r++) { + if (sCharacterSet[s[r]] !== undefined) { + sCharacterSet[s[r]] = 1 + sCharacterSet[s[r]]; + } else { + sCharacterSet[s[r]] = 1; } - - return result - -}; \ No newline at end of file + + maxLength = Math.max(maxLength, sCharacterSet[s[r]]); + + if (r - l + 1 - maxLength > k) { + sCharacterSet[s[l]] -= 1; + l += 1; + } + + result = Math.max(result, r - l + 1); + } + + return result; +}; diff --git a/javascript/435-Non-overlapping-Intervals.js b/javascript/435-Non-overlapping-Intervals.js index a9f61d525..e72d7d108 100644 --- a/javascript/435-Non-overlapping-Intervals.js +++ b/javascript/435-Non-overlapping-Intervals.js @@ -1,17 +1,17 @@ -let eraseOverlapIntervals = function(intervals) { - intervals = intervals.sort((a, b) => a[0] - b[1]); +let eraseOverlapIntervals = function (intervals) { + intervals = intervals.sort((a, b) => a[0] - b[1]); - let currentEnd = intervals[0][1]; - let res = 0; + let currentEnd = intervals[0][1]; + let res = 0; - for(let i = 1; i < intervals.length; i++) { - if(currentEnd > intervals[i][0]) { - res += 1; - currentEnd = Math.min(intervals[i][1], currentEnd); - } else { - currentEnd = intervals[i][1]; - } + for (let i = 1; i < intervals.length; i++) { + if (currentEnd > intervals[i][0]) { + res += 1; + currentEnd = Math.min(intervals[i][1], currentEnd); + } else { + currentEnd = intervals[i][1]; } + } - return res; + return res; }; diff --git a/javascript/46-Permutations.js b/javascript/46-Permutations.js index 6f8b312af..d86c0a650 100644 --- a/javascript/46-Permutations.js +++ b/javascript/46-Permutations.js @@ -1,25 +1,25 @@ -function permute(nums) { - const res = []; - - if (nums.length === 1) { - return [nums.slice()]; - } - - for (const i of nums) { - let n = nums.shift(); - - let perms = permute(nums); - - for (const perm of perms) { - perm.push(n); - } - - perms.forEach((perm) => { - res.push(perm); - }); - - nums.push(n); - } - - return res; -} +function permute(nums) { + const res = []; + + if (nums.length === 1) { + return [nums.slice()]; + } + + for (const i of nums) { + let n = nums.shift(); + + let perms = permute(nums); + + for (const perm of perms) { + perm.push(n); + } + + perms.forEach((perm) => { + res.push(perm); + }); + + nums.push(n); + } + + return res; +} diff --git a/javascript/473-Matchsticks-To-Square.js b/javascript/473-Matchsticks-To-Square.js index 97ee247e9..5899006bd 100644 --- a/javascript/473-Matchsticks-To-Square.js +++ b/javascript/473-Matchsticks-To-Square.js @@ -1,47 +1,49 @@ -function check(arr){ - let temp = arr[0]; - for(let i = 1; i < arr.length; i++){ - if(arr[i] !== temp){ - return false; - } +function check(arr) { + let temp = arr[0]; + for (let i = 1; i < arr.length; i++) { + if (arr[i] !== temp) { + return false; } - return true; + } + return true; } /** * @param {number[]} matchsticks * @return {boolean} */ -var makesquare = function(matchsticks) { - let sides = new Array(4).fill(0), ans = false, size = 0; - - for(let i = 0; i < matchsticks.length; i++){ - size += matchsticks[i]; +var makesquare = function (matchsticks) { + let sides = new Array(4).fill(0), + ans = false, + size = 0; + + for (let i = 0; i < matchsticks.length; i++) { + size += matchsticks[i]; + } + let max_size = size / 4; + if (max_size - Math.floor(max_size) !== 0) return false; + + matchsticks = matchsticks.sort((a, b) => b - a); + + function backtrack(i) { + if (ans) return; + if (i >= matchsticks.length) { + if (check(sides)) { + ans = true; + } + return; } - let max_size = size / 4; - if((max_size - Math.floor(max_size)) !== 0)return false; - - matchsticks = matchsticks.sort((a,b)=>b-a); - - function backtrack(i){ - if(ans)return; - if(i >= matchsticks.length){ - if(check(sides)){ - ans = true; - } - return; - } - for(let j = 0; j < 4; j++){ - if(sides[j] + matchsticks[i] > max_size){ - continue; - } - sides[j] += matchsticks[i]; + for (let j = 0; j < 4; j++) { + if (sides[j] + matchsticks[i] > max_size) { + continue; + } + sides[j] += matchsticks[i]; - backtrack(i + 1); - sides[j] -= matchsticks[i]; - } + backtrack(i + 1); + sides[j] -= matchsticks[i]; } - backtrack(0); - - return ans; + } + backtrack(0); + + return ans; }; diff --git a/javascript/49-Group-Anagrams.js b/javascript/49-Group-Anagrams.js index 970be7bb6..01d6a73f0 100644 --- a/javascript/49-Group-Anagrams.js +++ b/javascript/49-Group-Anagrams.js @@ -7,9 +7,32 @@ /** @const {!Object} */ const CODES = { - a: 0, b: 1, c: 2, d: 3, e: 4, f: 5, g: 6, h: 7, i: 8, j: 9, - k: 10, l: 11, m: 12, n: 13, o: 14, p: 15, q: 16, r: 17, - s: 18, t: 19, u: 20, v: 21, w: 22, x: 23, y: 24, z: 25 + a: 0, + b: 1, + c: 2, + d: 3, + e: 4, + f: 5, + g: 6, + h: 7, + i: 8, + j: 9, + k: 10, + l: 11, + m: 12, + n: 13, + o: 14, + p: 15, + q: 16, + r: 17, + s: 18, + t: 19, + u: 20, + v: 21, + w: 22, + x: 23, + y: 24, + z: 25, }; /** @@ -17,21 +40,20 @@ const CODES = { * @return {string[][]} */ function groupAnagrams(words) { - - const map = Object.create(null); - for (const word of words) { - const hash = hashWord(word); - if (!(hash in map)) { - map[hash] = []; - } - map[hash].push(word); + const map = Object.create(null); + for (const word of words) { + const hash = hashWord(word); + if (!(hash in map)) { + map[hash] = []; } - - const groups = []; - for (const key in map) { - groups.push(map[key]); - } - return groups; + map[hash].push(word); + } + + const groups = []; + for (const key in map) { + groups.push(map[key]); + } + return groups; } /** @@ -39,11 +61,11 @@ function groupAnagrams(words) { * @return {string} */ function hashWord(word) { - const hash = new Array(26).fill(0); - for (const ch of word) { - ++hash[CODES[ch]]; - } - return hash.toString(); + const hash = new Array(26).fill(0); + for (const ch of word) { + ++hash[CODES[ch]]; + } + return hash.toString(); } ////////////////////////////////////////////////////////////////////////////// @@ -61,7 +83,7 @@ const groupAnagrams = (strs) => { const result = []; const map = new Map(); for (let i = 0; i < strs.length; i++) { - const sorted = strs[i].split("").sort().join(""); + const sorted = strs[i].split('').sort().join(''); //! we are just splitting the string and sorting it and joining it back if (map.has(sorted)) { map.get(sorted).push(strs[i]); //! if the map has the sorted string, we push the string into the array diff --git a/javascript/49-Rotate-Image.js b/javascript/49-Rotate-Image.js index 7508b0a8d..50f6f8e9d 100644 --- a/javascript/49-Rotate-Image.js +++ b/javascript/49-Rotate-Image.js @@ -2,29 +2,29 @@ * @param {number[][]} matrix * @return {void} Do not return anything, modify matrix in-place instead. */ -var rotate = function(matrix) { - transpose(matrix); - reflect(matrix); +var rotate = function (matrix) { + transpose(matrix); + reflect(matrix); }; -var transpose = function(matrix) { - let n = matrix.length; - for (let i = 0; i < n; i++) { - for (let j = i + 1; j < n; j++) { - let temp = matrix[j][i]; - matrix[j][i] = matrix[i][j]; - matrix[i][j] = temp; - } +var transpose = function (matrix) { + let n = matrix.length; + for (let i = 0; i < n; i++) { + for (let j = i + 1; j < n; j++) { + let temp = matrix[j][i]; + matrix[j][i] = matrix[i][j]; + matrix[i][j] = temp; } -} + } +}; -var reflect = function(matrix) { - let n = matrix.length; - for (let i = 0; i < n; i++) { - for (let j = 0; j < n / 2; j++) { - let temp = matrix[i][j]; - matrix[i][j] = matrix[i][n - j - 1]; - matrix[i][n - j - 1] = temp; - } +var reflect = function (matrix) { + let n = matrix.length; + for (let i = 0; i < n; i++) { + for (let j = 0; j < n / 2; j++) { + let temp = matrix[i][j]; + matrix[i][j] = matrix[i][n - j - 1]; + matrix[i][n - j - 1] = temp; } -} + } +}; diff --git a/javascript/5-Longest-Palindromic-Substring.js b/javascript/5-Longest-Palindromic-Substring.js index 573ff8c41..aa5c1447f 100644 --- a/javascript/5-Longest-Palindromic-Substring.js +++ b/javascript/5-Longest-Palindromic-Substring.js @@ -1,34 +1,34 @@ -function longestPalindrome(s) { - let res = ""; - let resLen = 0; - - for (let i = 0; i < s.length; i++) { - let l = i; - let r = i; - - while (l >= 0 && r < s.length && s[l] === s[r]) { - if (r - l + 1 > resLen) { - res = s.slice(l, r + 1); - resLen = r - l + 1; - } - - l -= 1; - r += 1; - } - - l = i; - r = i + 1; - - while (l >= 0 && r < s.length && s[l] === s[r]) { - if (r - l + 1 > resLen) { - res = s.slice(l, r + 1); - resLen = r - l + 1; - } - - l -= 1; - r += 1; - } - } - - return res; -} +function longestPalindrome(s) { + let res = ''; + let resLen = 0; + + for (let i = 0; i < s.length; i++) { + let l = i; + let r = i; + + while (l >= 0 && r < s.length && s[l] === s[r]) { + if (r - l + 1 > resLen) { + res = s.slice(l, r + 1); + resLen = r - l + 1; + } + + l -= 1; + r += 1; + } + + l = i; + r = i + 1; + + while (l >= 0 && r < s.length && s[l] === s[r]) { + if (r - l + 1 > resLen) { + res = s.slice(l, r + 1); + resLen = r - l + 1; + } + + l -= 1; + r += 1; + } + } + + return res; +} diff --git a/javascript/50. Pow(x, n).js b/javascript/50. Pow(x, n).js index 9bf629f1e..464b81bd2 100644 --- a/javascript/50. Pow(x, n).js +++ b/javascript/50. Pow(x, n).js @@ -3,21 +3,17 @@ * @param {number} n * @return {number} */ -var myPow = function(x, n) { - // return Math.pow(x,n).toFixed(5) // One line solution - - if(x === 1.0 || n === 0) return 1 - - if(n === 1) return x - - else if(n % 2 === 0){ - return myPow(x * x, n / 2) - } - else if(n % 2 === 1){ - return x * myPow(x, n - 1) - } - else { - return 1 / myPow(x, -n) - } - +var myPow = function (x, n) { + // return Math.pow(x,n).toFixed(5) // One line solution + + if (x === 1.0 || n === 0) return 1; + + if (n === 1) return x; + else if (n % 2 === 0) { + return myPow(x * x, n / 2); + } else if (n % 2 === 1) { + return x * myPow(x, n - 1); + } else { + return 1 / myPow(x, -n); + } }; diff --git a/javascript/51-solveNQueens.js b/javascript/51-solveNQueens.js index 35b3dd3ba..8abe65ed2 100644 --- a/javascript/51-solveNQueens.js +++ b/javascript/51-solveNQueens.js @@ -11,7 +11,7 @@ function solveNQueens(n) { if (r === n) { for (let row of board) { - temp.push(row.join('')) + temp.push(row.join('')); } res.push(temp); @@ -26,16 +26,16 @@ function solveNQueens(n) { col.add(c); posDiag.add(r + c); negDiag.add(r - c); - board[r][c] = "Q"; + board[r][c] = 'Q'; backtrack(r + 1); col.delete(c); posDiag.delete(r + c); negDiag.delete(r - c); - board[r][c] = "."; + board[r][c] = '.'; } } backtrack(0); return res; -} \ No newline at end of file +} diff --git a/javascript/52-totalNQueens.js b/javascript/52-totalNQueens.js index 48977ea84..084d75df3 100644 --- a/javascript/52-totalNQueens.js +++ b/javascript/52-totalNQueens.js @@ -30,4 +30,4 @@ var totalNQueens = function (n) { } backtrack(0); return res; -} \ No newline at end of file +}; diff --git a/javascript/53-Maximum-Subarray.js b/javascript/53-Maximum-Subarray.js index 171bcbfc4..1cec9dc59 100644 --- a/javascript/53-Maximum-Subarray.js +++ b/javascript/53-Maximum-Subarray.js @@ -2,13 +2,13 @@ * @param {number[]} nums * @return {number} */ -var maxSubArray = function(nums) { - let curr = nums[0]; - let max = nums[0]; - - for (let i = 1; i < nums.length; i++) { - curr = Math.max(curr + nums[i], nums[i]); - max = Math.max(max, curr) - } - return max; +var maxSubArray = function (nums) { + let curr = nums[0]; + let max = nums[0]; + + for (let i = 1; i < nums.length; i++) { + curr = Math.max(curr + nums[i], nums[i]); + max = Math.max(max, curr); + } + return max; }; diff --git a/javascript/54-Spiral-Matrix.js b/javascript/54-Spiral-Matrix.js index 9d27c5f4c..b04066262 100644 --- a/javascript/54-Spiral-Matrix.js +++ b/javascript/54-Spiral-Matrix.js @@ -2,35 +2,37 @@ * @param {number[][]} matrix * @return {number[]} */ -var spiralOrder = function(matrix) { - const results = [] - let startRow = 0, startCol = 0, endRow = matrix.length-1, endCol = matrix[0].length-1; - - while(results.length < matrix.length * matrix[0].length) { - - for(let col = startCol; col <= endCol; col++ ) { - results.push(matrix[startRow][col]) - } - - for(let row = startRow + 1; row <= endRow; row++) { - results.push(matrix[row][endCol]) - } - - for(let col = endCol - 1; col >= startCol; col--) { - if(startRow === endRow) break; - results.push(matrix[endRow][col]) - } - - for(let row = endRow - 1; row >= startRow + 1; row--) { - if(endCol === startCol) break; - results.push(matrix[row][startCol]) - } - - startRow++ - startCol++ - endRow-- - endCol-- +var spiralOrder = function (matrix) { + const results = []; + let startRow = 0, + startCol = 0, + endRow = matrix.length - 1, + endCol = matrix[0].length - 1; + + while (results.length < matrix.length * matrix[0].length) { + for (let col = startCol; col <= endCol; col++) { + results.push(matrix[startRow][col]); } - - return results + + for (let row = startRow + 1; row <= endRow; row++) { + results.push(matrix[row][endCol]); + } + + for (let col = endCol - 1; col >= startCol; col--) { + if (startRow === endRow) break; + results.push(matrix[endRow][col]); + } + + for (let row = endRow - 1; row >= startRow + 1; row--) { + if (endCol === startCol) break; + results.push(matrix[row][startCol]); + } + + startRow++; + startCol++; + endRow--; + endCol--; + } + + return results; }; diff --git a/javascript/543-Diameter-Of-Binary-Tree.js b/javascript/543-Diameter-Of-Binary-Tree.js index f3e93e471..e76e2a7d7 100644 --- a/javascript/543-Diameter-Of-Binary-Tree.js +++ b/javascript/543-Diameter-Of-Binary-Tree.js @@ -10,19 +10,19 @@ * @param {TreeNode} root * @return {number} */ -var diameterOfBinaryTree = function(root) { - let diameter = 0; - - function dfs(root){ - if(root == null) return -1; - - const left = dfs(root.left) - const right = dfs(root.right) - diameter = Math.max(diameter, 2 + left + right); - - return 1 + Math.max(left, right); - } - dfs(root); - - return diameter; +var diameterOfBinaryTree = function (root) { + let diameter = 0; + + function dfs(root) { + if (root == null) return -1; + + const left = dfs(root.left); + const right = dfs(root.right); + diameter = Math.max(diameter, 2 + left + right); + + return 1 + Math.max(left, right); + } + dfs(root); + + return diameter; }; diff --git a/javascript/55-Jump-Game.js b/javascript/55-Jump-Game.js index b11205176..772aae55c 100644 --- a/javascript/55-Jump-Game.js +++ b/javascript/55-Jump-Game.js @@ -2,18 +2,14 @@ * @param {number[]} nums * @return {boolean} */ -var canJump = function(nums) { - - let goal = nums.length - 1; - - for(let i=nums.length-2;i>=0;i--){ - if(i+nums[i] >= goal){ - goal = i; - } +var canJump = function (nums) { + let goal = nums.length - 1; + + for (let i = nums.length - 2; i >= 0; i--) { + if (i + nums[i] >= goal) { + goal = i; } - if(goal === 0) - return true; - else - return false; - + } + if (goal === 0) return true; + else return false; }; diff --git a/javascript/56-Merge-Intervals.js b/javascript/56-Merge-Intervals.js index ebacd2a10..7cffdeac5 100644 --- a/javascript/56-Merge-Intervals.js +++ b/javascript/56-Merge-Intervals.js @@ -13,4 +13,4 @@ var merge = function (intervals) { } } return res; -}; \ No newline at end of file +}; diff --git a/javascript/567-Permutation-In-String.js b/javascript/567-Permutation-In-String.js index 2896d8465..a0271df06 100644 --- a/javascript/567-Permutation-In-String.js +++ b/javascript/567-Permutation-In-String.js @@ -14,68 +14,66 @@ * @return {boolean} */ function checkInclusion(s1, s2) { - - if (s1.length > s2.length) { - return false; + if (s1.length > s2.length) { + return false; + } + + const s1Chars = Object.create(null); + const s2Chars = Object.create(null); + + for (const ch of s1) { + if (!(ch in s1Chars)) { + s1Chars[ch] = 0; + s2Chars[ch] = 0; + } + ++s1Chars[ch]; + } + + for (let i = 0; i < s1.length; ++i) { + const ch = s2[i]; + if (ch in s1Chars) { + ++s2Chars[ch]; } - - const s1Chars = Object.create(null); - const s2Chars = Object.create(null); - - for (const ch of s1) { - if (!(ch in s1Chars)) { - s1Chars[ch] = 0; - s2Chars[ch] = 0; - } - ++s1Chars[ch]; + } + + let matches = 0; + let matched = 0; + + for (const ch in s1Chars) { + if (s1Chars[ch] === s2Chars[ch]) { + ++matches; } - - for (let i = 0; i < s1.length; ++i) { - const ch = s2[i]; - if (ch in s1Chars) { - ++s2Chars[ch]; - } + ++matched; + } + + const last = s2.length - s1.length; + + for (let i = 0; i < last; ++i) { + if (matches === matched) { + return true; } - - let matches = 0; - let matched = 0; - - for (const ch in s1Chars) { - if (s1Chars[ch] === s2Chars[ch]) { - ++matches; - } - ++matched; + + const ch1 = s2[i]; + const ch2 = s2[i + s1.length]; + + if (ch1 in s1Chars) { + if (s1Chars[ch1] === s2Chars[ch1]--) { + --matches; + } else if (s1Chars[ch1] === s2Chars[ch1]) { + ++matches; + } } - - const last = s2.length - s1.length; - - for (let i = 0; i < last; ++i) { - - if (matches === matched) { - return true; - } - - const ch1 = s2[i]; - const ch2 = s2[i + s1.length]; - - if (ch1 in s1Chars) { - if (s1Chars[ch1] === s2Chars[ch1]--) { - --matches; - } else if (s1Chars[ch1] === s2Chars[ch1]) { - ++matches; - } - } - - if (ch2 in s1Chars) { - if (s1Chars[ch2] === s2Chars[ch2]++) { - --matches; - } else if (s1Chars[ch2] === s2Chars[ch2]) { - ++matches; - } - } + + if (ch2 in s1Chars) { + if (s1Chars[ch2] === s2Chars[ch2]++) { + --matches; + } else if (s1Chars[ch2] === s2Chars[ch2]) { + ++matches; + } } - - return matches === matched; + } + + return matches === matched; } ////////////////////////////////////////////////////////////////////////////// @@ -94,65 +92,62 @@ function checkInclusion(s1, s2) { * @return {boolean} */ function checkInclusion(s1, s2) { - - if (s1.length > s2.length) { - return false; + if (s1.length > s2.length) { + return false; + } + + const s1Chars = Object.create(null); + + for (const ch of s1) { + if (!(ch in s1Chars)) { + s1Chars[ch] = 0; } - - const s1Chars = Object.create(null); - - for (const ch of s1) { - if (!(ch in s1Chars)) { - s1Chars[ch] = 0; - } - ++s1Chars[ch]; + ++s1Chars[ch]; + } + + const last = s2.length - s1.length; + let i = 0; + + while (i <= last) { + while (i <= last && !(s2[i] in s1Chars)) { + ++i; } - - const last = s2.length - s1.length; - let i = 0; - - while (i <= last) { - - while (i <= last && !(s2[i] in s1Chars)) { - ++i; - } - - if (i > last) { - return false; - } - - const subChars = Object.create(null); - let j = i; - - while (j < s2.length && s2[j] in s1Chars) { - - const ch = s2[j]; - - if (!(ch in subChars)) { - subChars[ch] = 0; - } - ++subChars[ch]; - - if (subChars[ch] > s1Chars[ch]) { - break; - } - - ++j; - } - - if (s1.length === j - i) { - return true; - } - - if (j < s2.length && s2[j] in s1Chars) { - while (s2[i] !== s2[j]) { - ++i; - } - ++i; - } else { - i = j; - } + + if (i > last) { + return false; } - - return false; + + const subChars = Object.create(null); + let j = i; + + while (j < s2.length && s2[j] in s1Chars) { + const ch = s2[j]; + + if (!(ch in subChars)) { + subChars[ch] = 0; + } + ++subChars[ch]; + + if (subChars[ch] > s1Chars[ch]) { + break; + } + + ++j; + } + + if (s1.length === j - i) { + return true; + } + + if (j < s2.length && s2[j] in s1Chars) { + while (s2[i] !== s2[j]) { + ++i; + } + ++i; + } else { + i = j; + } + } + + return false; } diff --git a/javascript/57-Insert-Interval.js b/javascript/57-Insert-Interval.js index b6f09fd3b..e8c107b30 100644 --- a/javascript/57-Insert-Interval.js +++ b/javascript/57-Insert-Interval.js @@ -1,26 +1,26 @@ -let insert = function(intervals, newInterval) { - let res = []; - let isAdded = false; +let insert = function (intervals, newInterval) { + let res = []; + let isAdded = false; - intervals.forEach(int => { - if (int[0] > newInterval[1]) { - if (!isAdded) { - res.push(newInterval); - isAdded = true; - } - - res.push(int); - } else if (int[1] < newInterval[0]) { - res.push(int); - } else { - newInterval[0] = Math.min(newInterval[0], int[0]); - newInterval[1] = Math.max(newInterval[1], int[1]); - } - }); - - if (!isAdded) { + intervals.forEach((int) => { + if (int[0] > newInterval[1]) { + if (!isAdded) { res.push(newInterval); + isAdded = true; + } + + res.push(int); + } else if (int[1] < newInterval[0]) { + res.push(int); + } else { + newInterval[0] = Math.min(newInterval[0], int[0]); + newInterval[1] = Math.max(newInterval[1], int[1]); } + }); + + if (!isAdded) { + res.push(newInterval); + } - return res; + return res; }; diff --git a/javascript/572-Subtree-of-Another-Tree.js b/javascript/572-Subtree-of-Another-Tree.js index 1820a9534..820b21584 100644 --- a/javascript/572-Subtree-of-Another-Tree.js +++ b/javascript/572-Subtree-of-Another-Tree.js @@ -11,24 +11,20 @@ * @param {TreeNode} subRoot * @return {boolean} */ -var isSubtree = function(root, subRoot) { - - // given two nodes are they the same? - const isSame = (n1, n2) => { - if (!n1 && !n2) return true; - if (!n1 || !n2 || n1.val !== n2.val) return false; - return isSame(n1.left, n2.left) && isSame(n1.right, n2.right); - } - - // check if subRoot is subtree of root: - const DFS = (node) => { - if (!node) return false; - if (isSame(node, subRoot)) return true; - return DFS(node.left) || DFS(node.right); - } - - - return DFS(root); - - +var isSubtree = function (root, subRoot) { + // given two nodes are they the same? + const isSame = (n1, n2) => { + if (!n1 && !n2) return true; + if (!n1 || !n2 || n1.val !== n2.val) return false; + return isSame(n1.left, n2.left) && isSame(n1.right, n2.right); + }; + + // check if subRoot is subtree of root: + const DFS = (node) => { + if (!node) return false; + if (isSame(node, subRoot)) return true; + return DFS(node.left) || DFS(node.right); + }; + + return DFS(root); }; diff --git a/javascript/62-Unique-Paths.js b/javascript/62-Unique-Paths.js index 8f9836892..104a122a0 100644 --- a/javascript/62-Unique-Paths.js +++ b/javascript/62-Unique-Paths.js @@ -1,15 +1,15 @@ -function uniquePaths(m, n) { - let row = new Array(n).fill(1); - - for (let i = 0; i < m - 1; i++) { - let newRow = new Array(n).fill(1); - - for (let j = n - 2; j > -1; j--) { - newRow[j] = newRow[j + 1] + row[j]; - } - - row = newRow; - } - - return row[0]; -} +function uniquePaths(m, n) { + let row = new Array(n).fill(1); + + for (let i = 0; i < m - 1; i++) { + let newRow = new Array(n).fill(1); + + for (let j = n - 2; j > -1; j--) { + newRow[j] = newRow[j + 1] + row[j]; + } + + row = newRow; + } + + return row[0]; +} diff --git a/javascript/647-Palindromic-Substrings.js b/javascript/647-Palindromic-Substrings.js index e3ee9ede7..b77823d57 100644 --- a/javascript/647-Palindromic-Substrings.js +++ b/javascript/647-Palindromic-Substrings.js @@ -1,25 +1,25 @@ -function countSubstrings(s) { - let res = 0; - - for (let i = 0; i < s.length; i++) { - let l = i; - let r = i; - - while (l >= 0 && r < s.length && s[l] === s[r]) { - res += 1; - l -= 1; - r += 1; - } - - l = i; - r = i + 1; - - while (l >= 0 && r < s.length && s[l] === s[r]) { - res += 1; - l -= 1; - r += 1; - } - } - - return res; -} +function countSubstrings(s) { + let res = 0; + + for (let i = 0; i < s.length; i++) { + let l = i; + let r = i; + + while (l >= 0 && r < s.length && s[l] === s[r]) { + res += 1; + l -= 1; + r += 1; + } + + l = i; + r = i + 1; + + while (l >= 0 && r < s.length && s[l] === s[r]) { + res += 1; + l -= 1; + r += 1; + } + } + + return res; +} diff --git a/javascript/66-plus-one.js b/javascript/66-plus-one.js index 462ea40f6..2a0685146 100644 --- a/javascript/66-plus-one.js +++ b/javascript/66-plus-one.js @@ -2,15 +2,15 @@ * @param {number[]} digits * @return {number[]} */ - var plusOne = function(digits) { - for (let i = digits.length-1 ; i >= 0 ; i--) { - if (digits[i] !== 9) { - digits[i]++ - return digits - } else { - digits[i] = 0 - } +var plusOne = function (digits) { + for (let i = digits.length - 1; i >= 0; i--) { + if (digits[i] !== 9) { + digits[i]++; + return digits; + } else { + digits[i] = 0; } - digits.unshift(1) - return digits -}; \ No newline at end of file + } + digits.unshift(1); + return digits; +}; diff --git a/javascript/695-Max-Area-Of-Island.js b/javascript/695-Max-Area-Of-Island.js index 5312e5160..d83834d3d 100644 --- a/javascript/695-Max-Area-Of-Island.js +++ b/javascript/695-Max-Area-Of-Island.js @@ -2,35 +2,35 @@ * @param {number[][]} grid * @return {number} */ -var maxAreaOfIsland = function(grid) { - function find(x, y) { - if (grid[y] === undefined || grid[y][x] === undefined) { - return 0; - } - - if (grid[y][x] === 0) { - return 0; - } - - grid[y][x] = 0; - - let square = 1; - - square += find(x + 1, y); - square += find(x - 1, y); - square += find(x, y + 1); - square += find(x, y - 1); - - return square; +var maxAreaOfIsland = function (grid) { + function find(x, y) { + if (grid[y] === undefined || grid[y][x] === undefined) { + return 0; } - - let max = 0; - - for (let y = 0; y < grid.length; y++) { - for (let x = 0; x < grid[0].length; x++) { - max = Math.max(max, find(x, y)); - } + + if (grid[y][x] === 0) { + return 0; } - - return max; + + grid[y][x] = 0; + + let square = 1; + + square += find(x + 1, y); + square += find(x - 1, y); + square += find(x, y + 1); + square += find(x, y - 1); + + return square; + } + + let max = 0; + + for (let y = 0; y < grid.length; y++) { + for (let x = 0; x < grid[0].length; x++) { + max = Math.max(max, find(x, y)); + } + } + + return max; }; diff --git a/javascript/70-Climbing-Stairs.js b/javascript/70-Climbing-Stairs.js index 2d02c4faf..ec9b57e0b 100644 --- a/javascript/70-Climbing-Stairs.js +++ b/javascript/70-Climbing-Stairs.js @@ -2,22 +2,22 @@ * @param {number} n * @return {number} */ -var climbStairs = function(n) { - const memoized = climb(); - return memoized(n); +var climbStairs = function (n) { + const memoized = climb(); + return memoized(n); }; function climb() { - let cache = {}; - - return function climbStairs(n) { - if (n in cache) { - return cache[n]; - } else if (n >= 1 && n < 4) { - return n; - } else { - cache[n] = climbStairs(n-2) + climbStairs(n-1); - return cache[n]; - } + let cache = {}; + + return function climbStairs(n) { + if (n in cache) { + return cache[n]; + } else if (n >= 1 && n < 4) { + return n; + } else { + cache[n] = climbStairs(n - 2) + climbStairs(n - 1); + return cache[n]; } + }; } diff --git a/javascript/703-Kth-Largest-Element-In-A-Stream.js b/javascript/703-Kth-Largest-Element-In-A-Stream.js index 871026cea..53ad9d80d 100644 --- a/javascript/703-Kth-Largest-Element-In-A-Stream.js +++ b/javascript/703-Kth-Largest-Element-In-A-Stream.js @@ -17,99 +17,99 @@ ////////////////////////////////////////////////////////////////////////////// class KthLargest { - /** - * @param {number} k - * @param {number[]} nums - * @constructor - */ - constructor(k, nums) { - this.heap = new MinHeap(nums, k); - } + /** + * @param {number} k + * @param {number[]} nums + * @constructor + */ + constructor(k, nums) { + this.heap = new MinHeap(nums, k); + } - /** - * @param {number} val - * @return {number} - */ - add(val) { - this.heap.add(val); - return this.heap.getMin(); - } + /** + * @param {number} val + * @return {number} + */ + add(val) { + this.heap.add(val); + return this.heap.getMin(); + } } class MinHeap { - /** - * @param {number[]} nums - * @param {number} size - * @constructor - */ - constructor(nums, size) { - this.size = size; - this.length = 0; - this.heap = []; - for (const num of nums) { - this.add(num); - } + /** + * @param {number[]} nums + * @param {number} size + * @constructor + */ + constructor(nums, size) { + this.size = size; + this.length = 0; + this.heap = []; + for (const num of nums) { + this.add(num); } - - /** - * @param {number} num - * @return {void} - */ - add(num) { - if (this.length < this.size) { - ++this.length; - this.heap.push(num); - this.siftUp(this.length - 1); - } else if (num > this.heap[0]) { - this.heap[0] = num; - this.siftDown(0); - } - } - - /** - * @return {number} - */ - getMin() { - return this.heap[0]; + } + + /** + * @param {number} num + * @return {void} + */ + add(num) { + if (this.length < this.size) { + ++this.length; + this.heap.push(num); + this.siftUp(this.length - 1); + } else if (num > this.heap[0]) { + this.heap[0] = num; + this.siftDown(0); } - - /** - * @param {number} i - * @return {void} - */ - siftDown(i) { - const length = this.length; - const heap = this.heap; - let k = i * 2 + 1; - while (k < length) { - if (k + 1 < length && heap[k + 1] < heap[k]) { - ++k; - } - if (heap[i] <= heap[k]) { - return; - } - [ heap[i], heap[k] ] = [ heap[k], heap[i] ]; - i = k; - k = i * 2 + 1; - } + } + + /** + * @return {number} + */ + getMin() { + return this.heap[0]; + } + + /** + * @param {number} i + * @return {void} + */ + siftDown(i) { + const length = this.length; + const heap = this.heap; + let k = i * 2 + 1; + while (k < length) { + if (k + 1 < length && heap[k + 1] < heap[k]) { + ++k; + } + if (heap[i] <= heap[k]) { + return; + } + [heap[i], heap[k]] = [heap[k], heap[i]]; + i = k; + k = i * 2 + 1; } - - /** - * @param {number} i - * @return {void} - */ - siftUp(i) { - const heap = this.heap; - let p = Math.floor((i - 1) / 2); - while (i > 0 && heap[i] < heap[p]) { - [ heap[i], heap[p] ] = [ heap[p], heap[i] ]; - i = p; - p = Math.floor((i - 1) / 2); - } + } + + /** + * @param {number} i + * @return {void} + */ + siftUp(i) { + const heap = this.heap; + let p = Math.floor((i - 1) / 2); + while (i > 0 && heap[i] < heap[p]) { + [heap[i], heap[p]] = [heap[p], heap[i]]; + i = p; + p = Math.floor((i - 1) / 2); } + } } -/** +/** * Your KthLargest object will be instantiated and called as such: * var obj = new KthLargest(k, nums) * var param_1 = obj.add(val) @@ -129,42 +129,42 @@ class MinHeap { ////////////////////////////////////////////////////////////////////////////// class KthLargest { - /** - * @param {number} k - * @param {number[]} nums - * @constructor - */ - constructor(k, nums) { - this.nums = nums.sort((a,b) => b - a); - this.k = k; - } + /** + * @param {number} k + * @param {number[]} nums + * @constructor + */ + constructor(k, nums) { + this.nums = nums.sort((a, b) => b - a); + this.k = k; + } - /** - * @param {number} val - * @return {number} - */ - add(val) { - const nums = this.nums; - let l = 0; - let r = nums.length; - while (l <= r) { - const m = Math.floor((l + r) / 2); - if (val === nums[m]) { - l = m; - break; - } - if (val < nums[m]) { - l = m + 1; - } else { - r = m - 1; - } - } - nums.splice(l, 0, val); - return nums[this.k - 1]; + /** + * @param {number} val + * @return {number} + */ + add(val) { + const nums = this.nums; + let l = 0; + let r = nums.length; + while (l <= r) { + const m = Math.floor((l + r) / 2); + if (val === nums[m]) { + l = m; + break; + } + if (val < nums[m]) { + l = m + 1; + } else { + r = m - 1; + } } + nums.splice(l, 0, val); + return nums[this.k - 1]; + } } -/** +/** * Your KthLargest object will be instantiated and called as such: * var obj = new KthLargest(k, nums) * var param_1 = obj.add(val) diff --git a/javascript/704-Binary-Search.js b/javascript/704-Binary-Search.js index c334eac1e..3335329a4 100644 --- a/javascript/704-Binary-Search.js +++ b/javascript/704-Binary-Search.js @@ -4,24 +4,23 @@ * @return {number} */ var search = function (nums, target) { + let left = 0; + let right = nums.length - 1; - let left = 0; - let right = nums.length - 1; + while (left <= right) { + let middle = Math.floor((left + right) / 2); - while (left <= right) { - let middle = Math.floor((left + right) / 2); - - if (nums[middle] === target) { - return middle; - } else if (nums[middle] < target) { - left = middle + 1; - } else { - right = middle - 1; - } + if (nums[middle] === target) { + return middle; + } else if (nums[middle] < target) { + left = middle + 1; + } else { + right = middle - 1; } + } - return -1; + return -1; }; // Runtime: 98 ms, faster than 34.02% of JavaScript online submissions for Binary Search. -// Memory Usage: 44.3 MB, less than 99.18% of JavaScript online submissions for Binary Search. \ No newline at end of file +// Memory Usage: 44.3 MB, less than 99.18% of JavaScript online submissions for Binary Search. diff --git a/javascript/72-Edit-Distance.js b/javascript/72-Edit-Distance.js index 7759c2848..9fc7f7a19 100644 --- a/javascript/72-Edit-Distance.js +++ b/javascript/72-Edit-Distance.js @@ -10,33 +10,31 @@ * @return {number} */ function minDistance(word1, word2) { - const len1 = word1.length; - const len2 = word2.length; - - if (!len1 || !len2) { - return len1 || len2; - } - - const dp = new Array(len1 + 1).fill() - .map(() => new Array(len2 + 1)); - - for (let i = 0; i <= len1; ++i) { - dp[i][0] = i; - } - for (let i = 0; i <= len2; ++i) { - dp[0][i] = i; - } - - for (let i = 1; i <= len1; ++i) { - for (let j = 1; j <= len2; ++j) { - const a = dp[i - 1][j] + 1; - const b = dp[i][j - 1] + 1; - const c = word1[i - 1] === word2[j - 1] - ? dp[i - 1][j - 1] - : dp[i - 1][j - 1] + 1; - dp[i][j] = Math.min(a, b, c); - } + const len1 = word1.length; + const len2 = word2.length; + + if (!len1 || !len2) { + return len1 || len2; + } + + const dp = new Array(len1 + 1).fill().map(() => new Array(len2 + 1)); + + for (let i = 0; i <= len1; ++i) { + dp[i][0] = i; + } + for (let i = 0; i <= len2; ++i) { + dp[0][i] = i; + } + + for (let i = 1; i <= len1; ++i) { + for (let j = 1; j <= len2; ++j) { + const a = dp[i - 1][j] + 1; + const b = dp[i][j - 1] + 1; + const c = + word1[i - 1] === word2[j - 1] ? dp[i - 1][j - 1] : dp[i - 1][j - 1] + 1; + dp[i][j] = Math.min(a, b, c); } - - return dp[len1][len2]; + } + + return dp[len1][len2]; } diff --git a/javascript/73-Set-Matrix-Zeroes.js b/javascript/73-Set-Matrix-Zeroes.js index 36068902c..b4d9f04a3 100644 --- a/javascript/73-Set-Matrix-Zeroes.js +++ b/javascript/73-Set-Matrix-Zeroes.js @@ -2,25 +2,24 @@ * @param {number[][]} matrix * @return {void} Do not return anything, modify matrix in-place instead. */ -var setZeroes = function(matrix) { - let row = new Array(matrix.length); - let col = new Array(matrix[0].length); - - for (let i = 0; i < row.length; i++) { - for (let j = 0; j < col.length; j++) { - if (matrix[i][j] === 0) { - row[i] = 0; - col[j] = 0; - } - } +var setZeroes = function (matrix) { + let row = new Array(matrix.length); + let col = new Array(matrix[0].length); + + for (let i = 0; i < row.length; i++) { + for (let j = 0; j < col.length; j++) { + if (matrix[i][j] === 0) { + row[i] = 0; + col[j] = 0; + } } - - for (let i = 0; i < row.length; i++) { - for (let j = 0; j < col.length; j++) { - if (row[i] == 0 || col[j] == 0) { - matrix[i][j] = 0; - } - } + } + + for (let i = 0; i < row.length; i++) { + for (let j = 0; j < col.length; j++) { + if (row[i] == 0 || col[j] == 0) { + matrix[i][j] = 0; + } } - + } }; diff --git a/javascript/739-daily-temperatures.js b/javascript/739-daily-temperatures.js index 821594d30..c9cfb5d15 100644 --- a/javascript/739-daily-temperatures.js +++ b/javascript/739-daily-temperatures.js @@ -2,18 +2,18 @@ * @param {number[]} temperatures * @return {number[]} */ -const dailyTemperatures = function(temperatures) { - const output = Array(temperatures.length).fill(0) - - const stack = [] - - for (let i = 0; i < temperatures.length; i++) { - while (stack.length !== 0 && stack[stack.length - 1][0] < temperatures[i]) { - const [temp, idx] = stack.pop() - output[idx] = i - idx - } - stack.push([temperatures[i], i]) +const dailyTemperatures = function (temperatures) { + const output = Array(temperatures.length).fill(0); + + const stack = []; + + for (let i = 0; i < temperatures.length; i++) { + while (stack.length !== 0 && stack[stack.length - 1][0] < temperatures[i]) { + const [temp, idx] = stack.pop(); + output[idx] = i - idx; } - - return output + stack.push([temperatures[i], i]); + } + + return output; }; diff --git a/javascript/74-Search-A-2D-Matrix.js b/javascript/74-Search-A-2D-Matrix.js index 7748fbdbf..3db75d30e 100644 --- a/javascript/74-Search-A-2D-Matrix.js +++ b/javascript/74-Search-A-2D-Matrix.js @@ -9,29 +9,28 @@ * @return {boolean} */ function searchMatrix(matrix, target) { - - const width = matrix[0].length; - const height = matrix.length; - let i = 0; - let j = height * width - 1; - - while (i <= j) { - const m = Math.floor((i + j) / 2); - const r = Math.floor(m / width); - const c = m % width; - - if (matrix[r][c] === target) { - return true; - } - - if (matrix[r][c] < target) { - i = m + 1; - } else { - j = m - 1; - } + const width = matrix[0].length; + const height = matrix.length; + let i = 0; + let j = height * width - 1; + + while (i <= j) { + const m = Math.floor((i + j) / 2); + const r = Math.floor(m / width); + const c = m % width; + + if (matrix[r][c] === target) { + return true; } - - return false; + + if (matrix[r][c] < target) { + i = m + 1; + } else { + j = m - 1; + } + } + + return false; } ////////////////////////////////////////////////////////////////////////////// @@ -45,44 +44,43 @@ function searchMatrix(matrix, target) { * @return {boolean} */ function searchMatrix(matrix, target) { - - let row = -1; - let i = 0; - let j = matrix.length - 1; - - while (i <= j) { - let m = Math.floor((i + j) / 2); - if (target < matrix[m][0]) { - j = m - 1; - } else if (target === matrix[m][0] || target === top(matrix[m])) { - return true; - } else if (target < top(matrix[m])) { - row = m; - break; - } else { - i = m + 1; - } - } - - if (row < 0) { - return false; - } - - const vals = matrix[row]; - i = 1; - j = vals.length - 2; - - while (i <= j) { - let m = Math.floor((i + j) / 2); - if (target < vals[m]) { - j = m - 1; - } else if (target > vals[m]) { - i = m + 1; - } else { - return true; - } + let row = -1; + let i = 0; + let j = matrix.length - 1; + + while (i <= j) { + let m = Math.floor((i + j) / 2); + if (target < matrix[m][0]) { + j = m - 1; + } else if (target === matrix[m][0] || target === top(matrix[m])) { + return true; + } else if (target < top(matrix[m])) { + row = m; + break; + } else { + i = m + 1; } + } + + if (row < 0) { return false; + } + + const vals = matrix[row]; + i = 1; + j = vals.length - 2; + + while (i <= j) { + let m = Math.floor((i + j) / 2); + if (target < vals[m]) { + j = m - 1; + } else if (target > vals[m]) { + i = m + 1; + } else { + return true; + } + } + return false; } /** @@ -90,5 +88,5 @@ function searchMatrix(matrix, target) { * @return {*} */ function top(arr) { - return arr[arr.length - 1]; + return arr[arr.length - 1]; } diff --git a/javascript/746-Min-Cost-Climbing-Stairs.js b/javascript/746-Min-Cost-Climbing-Stairs.js index fa8cbeab9..f6effa83d 100644 --- a/javascript/746-Min-Cost-Climbing-Stairs.js +++ b/javascript/746-Min-Cost-Climbing-Stairs.js @@ -1,9 +1,9 @@ -function minCostClimbingStairs(cost) { - cost.push(0); - - for (let i = cost.length - 3; i > -1; i--) { - cost[i] += Math.min(cost[i + 1], cost[i + 2]); - } - - return Math.min(cost[0], cost[1]); -} +function minCostClimbingStairs(cost) { + cost.push(0); + + for (let i = cost.length - 3; i > -1; i--) { + cost[i] += Math.min(cost[i + 1], cost[i + 2]); + } + + return Math.min(cost[0], cost[1]); +} diff --git a/javascript/76-Minimum-Window-Substring.js b/javascript/76-Minimum-Window-Substring.js index 990a37b1d..3eafa01d6 100644 --- a/javascript/76-Minimum-Window-Substring.js +++ b/javascript/76-Minimum-Window-Substring.js @@ -3,7 +3,7 @@ var minWindow = function (str, target) { if (!acc[val]) acc[val] = 0; acc[val] += 1; return acc; - }, {}) + }, {}); let start = 0; let min = Infinity; @@ -31,5 +31,7 @@ var minWindow = function (str, target) { } } } - return min === Infinity ? '' : str.substring(subStringStart, subStringStart + min); -}; \ No newline at end of file + return min === Infinity + ? '' + : str.substring(subStringStart, subStringStart + min); +}; diff --git a/javascript/78-Subsets.js b/javascript/78-Subsets.js index 3b3ff83a5..1e5760bb0 100644 --- a/javascript/78-Subsets.js +++ b/javascript/78-Subsets.js @@ -1,20 +1,20 @@ -function subsets(nums) { - let res = []; - let subset = []; - function dfs(i) { - if (i >= nums.length) { - res.push(subset.slice()); - return; - } - - subset.push(nums[i]); - dfs(i + 1); - - subset.pop(); - dfs(i + 1); - } - - dfs(0); - - return res; -} +function subsets(nums) { + let res = []; + let subset = []; + function dfs(i) { + if (i >= nums.length) { + res.push(subset.slice()); + return; + } + + subset.push(nums[i]); + dfs(i + 1); + + subset.pop(); + dfs(i + 1); + } + + dfs(0); + + return res; +} diff --git a/javascript/79-Word-Search.js b/javascript/79-Word-Search.js index 437bd351f..bbbf67987 100644 --- a/javascript/79-Word-Search.js +++ b/javascript/79-Word-Search.js @@ -1,17 +1,16 @@ function dfs(board, i, j, remain) { - if (remain === "") return true; + if (remain === '') return true; if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return false; if (board[i][j] !== remain[0]) return false; let temp = board[i][j]; - board[i][j] = "-"; + board[i][j] = '-'; - let result = ( - dfs(board, i - 1, j, remain.slice(1)) - || dfs(board, i + 1, j, remain.slice(1)) - || dfs(board, i, j - 1, remain.slice(1)) - || dfs(board, i, j + 1, remain.slice(1)) - ) + let result = + dfs(board, i - 1, j, remain.slice(1)) || + dfs(board, i + 1, j, remain.slice(1)) || + dfs(board, i, j - 1, remain.slice(1)) || + dfs(board, i, j + 1, remain.slice(1)); board[i][j] = temp; return result; @@ -26,4 +25,4 @@ var exist = function (board, word) { } } return false; -}; \ No newline at end of file +}; diff --git a/javascript/84-Largest-Rectangle-in-Histogram.js b/javascript/84-Largest-Rectangle-in-Histogram.js index 7eefaeb03..6717b19ad 100644 --- a/javascript/84-Largest-Rectangle-in-Histogram.js +++ b/javascript/84-Largest-Rectangle-in-Histogram.js @@ -2,26 +2,26 @@ * @param {number[]} heights * @return {number} */ - var largestRectangleArea = function(heights) { - let largestArea = 0; - let stack = []; - - for (let i = 0; i< heights.length; i++){ - let start = i; - - while ( stack.length > 0 && stack[stack.length-1][1] > heights[i] ){ - let [lastI, lastH] = stack.pop(); - largestArea = Math.max(largestArea, lastH * (i-lastI)); - start = lastI; - } - - stack.push([ start, heights[i] ]); +var largestRectangleArea = function (heights) { + let largestArea = 0; + let stack = []; + + for (let i = 0; i < heights.length; i++) { + let start = i; + + while (stack.length > 0 && stack[stack.length - 1][1] > heights[i]) { + let [lastI, lastH] = stack.pop(); + largestArea = Math.max(largestArea, lastH * (i - lastI)); + start = lastI; } - - for (let j = 0; j < stack.length; j++){ - let currArea = stack[j][1] * (heights.length - stack[j][0]); - largestArea = Math.max(largestArea, currArea); - } - - return largestArea; -}; \ No newline at end of file + + stack.push([start, heights[i]]); + } + + for (let j = 0; j < stack.length; j++) { + let currArea = stack[j][1] * (heights.length - stack[j][0]); + largestArea = Math.max(largestArea, currArea); + } + + return largestArea; +}; diff --git a/javascript/853-Car-Fleet.js b/javascript/853-Car-Fleet.js index 0dd173e2d..e610fbd4a 100644 --- a/javascript/853-Car-Fleet.js +++ b/javascript/853-Car-Fleet.js @@ -1,25 +1,25 @@ -function carFleet(target, position, speed) { - const combined = position - .map((item, index) => { - return [item, speed[index]]; - }) - .sort((a, b) => a[0] - b[0]); - - const stack = []; - - for (let i = combined.length - 1; i > -1; i--) { - const p = combined[i][0]; - const s = combined[i][1]; - - stack.push((target - p) / s); - - if ( - stack.length >= 2 && - stack[stack.length - 1] <= stack[stack.length - 2] - ) { - stack.pop(); - } - } - - return stack.length; -} +function carFleet(target, position, speed) { + const combined = position + .map((item, index) => { + return [item, speed[index]]; + }) + .sort((a, b) => a[0] - b[0]); + + const stack = []; + + for (let i = combined.length - 1; i > -1; i--) { + const p = combined[i][0]; + const s = combined[i][1]; + + stack.push((target - p) / s); + + if ( + stack.length >= 2 && + stack[stack.length - 1] <= stack[stack.length - 2] + ) { + stack.pop(); + } + } + + return stack.length; +} diff --git a/javascript/875-Koko-Eating-Bananas.js b/javascript/875-Koko-Eating-Bananas.js index a90318871..ab53c87d6 100644 --- a/javascript/875-Koko-Eating-Bananas.js +++ b/javascript/875-Koko-Eating-Bananas.js @@ -9,26 +9,25 @@ * @return {number} */ function minEatingSpeed(piles, h) { - - let l = 0; - let r = Math.max.apply(Math, piles); - - if (piles.length === h) { - return r; + let l = 0; + let r = Math.max.apply(Math, piles); + + if (piles.length === h) { + return r; + } + + while (l < r) { + const m = Math.floor((l + r) / 2); + let hours = 0; + for (const pile of piles) { + hours += Math.ceil(pile / m); } - - while (l < r) { - const m = Math.floor((l + r) / 2); - let hours = 0; - for (const pile of piles) { - hours += Math.ceil(pile / m); - } - if (hours > h) { - l = m + 1; - } else { - r = m; - } + if (hours > h) { + l = m + 1; + } else { + r = m; } - - return l; -} \ No newline at end of file + } + + return l; +} diff --git a/javascript/9-Palindrome-Number.js b/javascript/9-Palindrome-Number.js index df0f55dbe..cd263b2a0 100644 --- a/javascript/9-Palindrome-Number.js +++ b/javascript/9-Palindrome-Number.js @@ -3,22 +3,19 @@ * @return {boolean} */ var isPalindrome = function (x) { + // Creates array from int characters + // 121 -> [1,2,1] + let arr = Array.from(String(x), Number); - // Creates array from int characters - // 121 -> [1,2,1] - let arr = Array.from(String(x), Number); - - // Uses two pointer - for (let i = 0; i < arr.length; i++) { - if (arr[i] !== arr[arr.length - 1 - i]) { - return false; - } + // Uses two pointer + for (let i = 0; i < arr.length; i++) { + if (arr[i] !== arr[arr.length - 1 - i]) { + return false; } + } - return true; + return true; }; - // Runtime: 302 ms, faster than 40.50% of JavaScript online submissions for Palindrome Number. // Memory Usage: 51.8 MB, less than 8.36% of JavaScript online submissions for Palindrome Number. - diff --git a/javascript/90-Subsets-II.js b/javascript/90-Subsets-II.js index a2dff03a8..2f69400d5 100644 --- a/javascript/90-Subsets-II.js +++ b/javascript/90-Subsets-II.js @@ -9,28 +9,26 @@ * @return {number[][]} */ function subsetsWithDup(nums) { - - nums.sort((a, b) => a - b); - const results = []; - const result = []; - getSubsets(); - return results; - - /** - * @param {number} start = `0` - * @return {void} - */ - function getSubsets(start = 0) { - - results.push(result.slice()); - - for (let i = start; i < nums.length; ++i) { - if (i !== start && nums[i] === nums[i - 1]) { - continue; - } - result.push(nums[i]); - getSubsets(i + 1); - result.pop(); - } + nums.sort((a, b) => a - b); + const results = []; + const result = []; + getSubsets(); + return results; + + /** + * @param {number} start = `0` + * @return {void} + */ + function getSubsets(start = 0) { + results.push(result.slice()); + + for (let i = start; i < nums.length; ++i) { + if (i !== start && nums[i] === nums[i - 1]) { + continue; + } + result.push(nums[i]); + getSubsets(i + 1); + result.pop(); } + } } diff --git a/javascript/91-Decode-Ways.js b/javascript/91-Decode-Ways.js index 475cd35fc..e6525f163 100644 --- a/javascript/91-Decode-Ways.js +++ b/javascript/91-Decode-Ways.js @@ -1,20 +1,20 @@ -function numDecodings(s) { - let dp = { - [s.length]: 1, - }; - - for (let i = s.length - 1; i > -1; i--) { - if (s[i] == "0") { - dp[i] = 0; - } else { - dp[i] = dp[i + 1]; - } - if ( - i + 1 < s.length && - (s[i] == "1" || (s[i] == "2" && "0123456".includes(s[i + 1]))) - ) { - dp[i] += dp[i + 2]; - } - } - return dp[0]; -} +function numDecodings(s) { + let dp = { + [s.length]: 1, + }; + + for (let i = s.length - 1; i > -1; i--) { + if (s[i] == '0') { + dp[i] = 0; + } else { + dp[i] = dp[i + 1]; + } + if ( + i + 1 < s.length && + (s[i] == '1' || (s[i] == '2' && '0123456'.includes(s[i + 1]))) + ) { + dp[i] += dp[i + 2]; + } + } + return dp[0]; +} diff --git a/javascript/97-Interleaving-String.js b/javascript/97-Interleaving-String.js index 87965a56b..ca97df730 100644 --- a/javascript/97-Interleaving-String.js +++ b/javascript/97-Interleaving-String.js @@ -11,35 +11,31 @@ * @return {boolean} */ function isInterleave(s1, s2, s3) { - - const l1 = s1.length; - const l2 = s2.length; - const l3 = s3.length; - - if (l1 + l2 !== l3) { - return false; - } - if (!s1 || !s2 || !s3) { - return (!s1 && !s2 && !s3) || ( - s1 - ? s1 === s3 - : s2 === s3 - ); - } - - const seen = new Array(l2 + 1); - seen[l2] = true; - - for (let i = l2 - 1; i >= 0; --i) { - seen[i] = seen[i + 1] && s2[i] === s3[l1 + i]; - } - for (let i = l1 - 1; i >= 0; --i) { - for (let j = l2; j >= 0; --j) { - seen[j] = (seen[j] && s1[i] === s3[i + j]) - || (j !== l2 && seen[j + 1] && s2[j] === s3[i + j]); - } + const l1 = s1.length; + const l2 = s2.length; + const l3 = s3.length; + + if (l1 + l2 !== l3) { + return false; + } + if (!s1 || !s2 || !s3) { + return (!s1 && !s2 && !s3) || (s1 ? s1 === s3 : s2 === s3); + } + + const seen = new Array(l2 + 1); + seen[l2] = true; + + for (let i = l2 - 1; i >= 0; --i) { + seen[i] = seen[i + 1] && s2[i] === s3[l1 + i]; + } + for (let i = l1 - 1; i >= 0; --i) { + for (let j = l2; j >= 0; --j) { + seen[j] = + (seen[j] && s1[i] === s3[i + j]) || + (j !== l2 && seen[j + 1] && s2[j] === s3[i + j]); } - return seen[0]; + } + return seen[0]; } ////////////////////////////////////////////////////////////////////////////// @@ -55,39 +51,34 @@ function isInterleave(s1, s2, s3) { * @return {boolean} */ function isInterleave(s1, s2, s3) { - - const l1 = s1.length; - const l2 = s2.length; - const l3 = s3.length; - - if (l1 + l2 !== l3) { - return false; - } - if (!s1 || !s2 || !s3) { - return (!s1 && !s2 && !s3) || ( - s1 - ? s1 === s3 - : s2 === s3 - ); - } - - const seen = new Array(l1 + 1).fill() - .map(() => new Array(l2 + 1)); - seen[l1][l2] = true; - - for (let i = l1 - 1; i >= 0; --i) { - seen[i][l2] = seen[i + 1][l2] && s1[i] === s3[i + l2]; - } + const l1 = s1.length; + const l2 = s2.length; + const l3 = s3.length; + + if (l1 + l2 !== l3) { + return false; + } + if (!s1 || !s2 || !s3) { + return (!s1 && !s2 && !s3) || (s1 ? s1 === s3 : s2 === s3); + } + + const seen = new Array(l1 + 1).fill().map(() => new Array(l2 + 1)); + seen[l1][l2] = true; + + for (let i = l1 - 1; i >= 0; --i) { + seen[i][l2] = seen[i + 1][l2] && s1[i] === s3[i + l2]; + } + for (let j = l2 - 1; j >= 0; --j) { + seen[l1][j] = seen[l1][j + 1] && s2[j] === s3[l1 + j]; + } + for (let i = l1 - 1; i >= 0; --i) { for (let j = l2 - 1; j >= 0; --j) { - seen[l1][j] = seen[l1][j + 1] && s2[j] === s3[l1 + j]; - } - for (let i = l1 - 1; i >= 0; --i) { - for (let j = l2 - 1; j >= 0; --j) { - seen[i][j] = (seen[i + 1][j] && s1[i] === s3[i + j]) - || (seen[i][j + 1] && s2[j] === s3[i + j]); - } + seen[i][j] = + (seen[i + 1][j] && s1[i] === s3[i + j]) || + (seen[i][j + 1] && s2[j] === s3[i + j]); } - return seen[0][0]; + } + return seen[0][0]; } ////////////////////////////////////////////////////////////////////////////// @@ -103,45 +94,34 @@ function isInterleave(s1, s2, s3) { * @return {boolean} */ function isInterleave(s1, s2, s3) { - - const l1 = s1.length; - const l2 = s2.length; - const l3 = s3.length; - - if (l1 + l2 !== l3) { - return false; - } - if (!s1 || !s2 || !s3) { - return (!s1 && !s2 && !s3) || ( - s1 - ? s1 === s3 - : s2 === s3 - ); - } - - const seen = new Array(l1 + 1).fill() - .map(() => new Array(l2 + 1)); - return checkStrings(); - - /** - * @param {number=} i = `0` - * @param {number=} j = `0` - * @param {number=} k = `0` - * @return {boolean} - */ - function checkStrings(i = 0, j = 0, k = 0) { - return k === l3 || ( - seen[i][j] !== undefined - ? seen[i][j] - : seen[i][j] = ( - i < l1 - && s1[i] === s3[k] - && checkStrings(i + 1, j, k + 1) - ) || ( - j < l2 - && s2[j] === s3[k] - && checkStrings(i, j + 1, k + 1) - ) - ); - } + const l1 = s1.length; + const l2 = s2.length; + const l3 = s3.length; + + if (l1 + l2 !== l3) { + return false; + } + if (!s1 || !s2 || !s3) { + return (!s1 && !s2 && !s3) || (s1 ? s1 === s3 : s2 === s3); + } + + const seen = new Array(l1 + 1).fill().map(() => new Array(l2 + 1)); + return checkStrings(); + + /** + * @param {number=} i = `0` + * @param {number=} j = `0` + * @param {number=} k = `0` + * @return {boolean} + */ + function checkStrings(i = 0, j = 0, k = 0) { + return ( + k === l3 || + (seen[i][j] !== undefined + ? seen[i][j] + : (seen[i][j] = + (i < l1 && s1[i] === s3[k] && checkStrings(i + 1, j, k + 1)) || + (j < l2 && s2[j] === s3[k] && checkStrings(i, j + 1, k + 1)))) + ); + } } diff --git a/javascript/973-K-Closest-Points-to-Origin.js b/javascript/973-K-Closest-Points-to-Origin.js index 55c69c342..5857f452d 100644 --- a/javascript/973-K-Closest-Points-to-Origin.js +++ b/javascript/973-K-Closest-Points-to-Origin.js @@ -1,177 +1,181 @@ -////////////////////////////////////////////////////////////////////////////// -// Sort with Custom Comparator -// Time: O(nlogn) -// Space: O(n) -////////////////////////////////////////////////////////////////////////////// - -/** - * @param {number[][]} points - * @param {number} k - * @return {number[][]} - */ -var kClosest = function(points, k) { - // Sort the array with a custom lambda comparator function - points.sort((a, b) => squaredDistance(a) - squaredDistance(b)); - - // Return the first k elements of the sorted array - return points.slice(0, k); -}; - -// Calculate and return the squared Euclidean distance -const squaredDistance = ([x, y]) => x ** 2 + y ** 2; - -////////////////////////////////////////////////////////////////////////////// -// Max Heap or Max Priority Queue -// Time: O(nlogk) -// Space: O(k) -////////////////////////////////////////////////////////////////////////////// - -/** - * @param {number[][]} points - * @param {number} k - * @return {number[][]} - */ -var kClosest = function(points, k) { - let maxPQ = new MaxPriorityQueue(); - for (let point of points) { - let dist = squaredDistance(point); - if (maxPQ.size() < k) { - // Fill the max PQ up to k points - maxPQ.enqueue(point, dist); - } else if (dist < maxPQ.front().priority) { - // If the max PQ is full and a closer point is found, - // discard the farthest point and add this one - maxPQ.dequeue(); - maxPQ.enqueue(point, dist); - } - } - - // Return all points stored in the max PQ - return maxPQ.toArray().map(el => el.element); -}; - -// Calculate and return the squared Euclidean distance -const squaredDistance = ([x,y]) => x ** 2 + y ** 2; - -////////////////////////////////////////////////////////////////////////////// -// Binary Search -// Time: O(n) -// Space: O(n) -////////////////////////////////////////////////////////////////////////////// - -/** - * @param {number[][]} points - * @param {number} k - * @return {number[][]} - */ -var kClosest = function(points, k) { - // Precompute the Euclidean distance for each point - let distances = points.map(euclideanDistance); - // Create a reference array of point indices - let remaining = points.map((_, i) => i); - // Define the initial binary search range - let low = 0, high = Math.max(...distances); - - // Perform a binary search of the distances - // to find the k closest points - let closest = [] - while (k) { - let mid = low + (high - low) / 2; - let [closer, farther] = splitDistances(remaining, distances, mid); - if (closer.length > k) { - // If more than k points are in the closer distances - // then discard the farther points and continue - remaining = closer; - high = mid; - } else { - // Add the closer points to the answer array and keep - // searching the farther distances for the remaining points - k -= closer.length; - closest.push(...closer); - remaining = farther; - low = mid; - } - } - - // Return the k closest points using the reference indices - return closest.map(i => points[i]); -}; - -var splitDistances = function(remaining, distances, mid) { - // Split the distances around the midpoint - // and return them in separate arrays - let closer = [], farther = []; - for (let index of remaining) { - if (distances[index] <= mid) { - closer.push(index); - } else { - farther.push(index); - } - } - return [closer, farther]; -}; - -// Calculate and return the squared Euclidean distance -const euclideanDistance = ([x,y]) => x ** 2 + y ** 2; - -////////////////////////////////////////////////////////////////////////////// -// QuickSelect -// Time: O(n) -// Space: O(1) -////////////////////////////////////////////////////////////////////////////// - -/** - * @param {number[][]} points - * @param {number} k - * @return {number[][]} - */ -var kClosest = function(points, k) { - return quickSelect(points, k) -}; - -var quickSelect = function(points, k) { - let left = 0, right = points.length - 1; - let pivotIndex = points.length; - while (pivotIndex !== k) { - // Repeatedly partition the array - // while narrowing in on the kth element - pivotIndex = partition(points, left, right); - if (pivotIndex < k) { - left = pivotIndex; - } else { - right = pivotIndex - 1; - } - } - - // Return the first k elements of the partially sorted array - return points.slice(0, k); -}; - -var partition = function(points, left, right) { - let pivot = choosePivot(points, left, right); - let pivotDist = squaredDistance(pivot); - while (left < right) { - // Iterate through the range and swap elements to make sure - // that all points closer than the pivot are to the left - if (squaredDistance(points[left]) >= pivotDist) { - [points[left], points[right]] = [points[right], points[left]]; - right--; - } else { - left++; - } - } - - // Ensure the left pointer is just past the end of - // the left range then return it as the new pivotIndex - if (squaredDistance(points[left]) < pivotDist) { - left++; - } - - return left; -}; - -// Choose a pivot element of the array -const choosePivot = (points, left, right) => points[left + ((right - left) >> 1)]; - -// Calculate and return the squared Euclidean distance -const squaredDistance = ([x,y]) => x ** 2 + y ** 2; +////////////////////////////////////////////////////////////////////////////// +// Sort with Custom Comparator +// Time: O(nlogn) +// Space: O(n) +////////////////////////////////////////////////////////////////////////////// + +/** + * @param {number[][]} points + * @param {number} k + * @return {number[][]} + */ +var kClosest = function (points, k) { + // Sort the array with a custom lambda comparator function + points.sort((a, b) => squaredDistance(a) - squaredDistance(b)); + + // Return the first k elements of the sorted array + return points.slice(0, k); +}; + +// Calculate and return the squared Euclidean distance +const squaredDistance = ([x, y]) => x ** 2 + y ** 2; + +////////////////////////////////////////////////////////////////////////////// +// Max Heap or Max Priority Queue +// Time: O(nlogk) +// Space: O(k) +////////////////////////////////////////////////////////////////////////////// + +/** + * @param {number[][]} points + * @param {number} k + * @return {number[][]} + */ +var kClosest = function (points, k) { + let maxPQ = new MaxPriorityQueue(); + for (let point of points) { + let dist = squaredDistance(point); + if (maxPQ.size() < k) { + // Fill the max PQ up to k points + maxPQ.enqueue(point, dist); + } else if (dist < maxPQ.front().priority) { + // If the max PQ is full and a closer point is found, + // discard the farthest point and add this one + maxPQ.dequeue(); + maxPQ.enqueue(point, dist); + } + } + + // Return all points stored in the max PQ + return maxPQ.toArray().map((el) => el.element); +}; + +// Calculate and return the squared Euclidean distance +const squaredDistance = ([x, y]) => x ** 2 + y ** 2; + +////////////////////////////////////////////////////////////////////////////// +// Binary Search +// Time: O(n) +// Space: O(n) +////////////////////////////////////////////////////////////////////////////// + +/** + * @param {number[][]} points + * @param {number} k + * @return {number[][]} + */ +var kClosest = function (points, k) { + // Precompute the Euclidean distance for each point + let distances = points.map(euclideanDistance); + // Create a reference array of point indices + let remaining = points.map((_, i) => i); + // Define the initial binary search range + let low = 0, + high = Math.max(...distances); + + // Perform a binary search of the distances + // to find the k closest points + let closest = []; + while (k) { + let mid = low + (high - low) / 2; + let [closer, farther] = splitDistances(remaining, distances, mid); + if (closer.length > k) { + // If more than k points are in the closer distances + // then discard the farther points and continue + remaining = closer; + high = mid; + } else { + // Add the closer points to the answer array and keep + // searching the farther distances for the remaining points + k -= closer.length; + closest.push(...closer); + remaining = farther; + low = mid; + } + } + + // Return the k closest points using the reference indices + return closest.map((i) => points[i]); +}; + +var splitDistances = function (remaining, distances, mid) { + // Split the distances around the midpoint + // and return them in separate arrays + let closer = [], + farther = []; + for (let index of remaining) { + if (distances[index] <= mid) { + closer.push(index); + } else { + farther.push(index); + } + } + return [closer, farther]; +}; + +// Calculate and return the squared Euclidean distance +const euclideanDistance = ([x, y]) => x ** 2 + y ** 2; + +////////////////////////////////////////////////////////////////////////////// +// QuickSelect +// Time: O(n) +// Space: O(1) +////////////////////////////////////////////////////////////////////////////// + +/** + * @param {number[][]} points + * @param {number} k + * @return {number[][]} + */ +var kClosest = function (points, k) { + return quickSelect(points, k); +}; + +var quickSelect = function (points, k) { + let left = 0, + right = points.length - 1; + let pivotIndex = points.length; + while (pivotIndex !== k) { + // Repeatedly partition the array + // while narrowing in on the kth element + pivotIndex = partition(points, left, right); + if (pivotIndex < k) { + left = pivotIndex; + } else { + right = pivotIndex - 1; + } + } + + // Return the first k elements of the partially sorted array + return points.slice(0, k); +}; + +var partition = function (points, left, right) { + let pivot = choosePivot(points, left, right); + let pivotDist = squaredDistance(pivot); + while (left < right) { + // Iterate through the range and swap elements to make sure + // that all points closer than the pivot are to the left + if (squaredDistance(points[left]) >= pivotDist) { + [points[left], points[right]] = [points[right], points[left]]; + right--; + } else { + left++; + } + } + + // Ensure the left pointer is just past the end of + // the left range then return it as the new pivotIndex + if (squaredDistance(points[left]) < pivotDist) { + left++; + } + + return left; +}; + +// Choose a pivot element of the array +const choosePivot = (points, left, right) => + points[left + ((right - left) >> 1)]; + +// Calculate and return the squared Euclidean distance +const squaredDistance = ([x, y]) => x ** 2 + y ** 2; diff --git a/javascript/98-Validate-Binary-Search-Tree.js b/javascript/98-Validate-Binary-Search-Tree.js index 3d7cad0de..ad478142a 100644 --- a/javascript/98-Validate-Binary-Search-Tree.js +++ b/javascript/98-Validate-Binary-Search-Tree.js @@ -11,16 +11,20 @@ * @return {boolean} */ - -var isValidBST = function(root) { - return validate(root, null, null); +var isValidBST = function (root) { + return validate(root, null, null); }; function validate(root, max, min) { - if (!root) { - return true; - } else if (max !== null && root.val >= max || min !== null && root.val <= min) { - return false; - } else - return validate(root.left, root.val, min) && validate(root.right, max, root.val); + if (!root) { + return true; + } else if ( + (max !== null && root.val >= max) || + (min !== null && root.val <= min) + ) { + return false; + } else + return ( + validate(root.left, root.val, min) && validate(root.right, max, root.val) + ); } diff --git a/javascript/981-Time-Based-Key-Value-Store.js b/javascript/981-Time-Based-Key-Value-Store.js index 2c19d7648..209b311aa 100644 --- a/javascript/981-Time-Based-Key-Value-Store.js +++ b/javascript/981-Time-Based-Key-Value-Store.js @@ -1,44 +1,43 @@ -var TimeMap = function() { - this.keyStore = {} +var TimeMap = function () { + this.keyStore = {}; }; -/** - * @param {string} key - * @param {string} value +/** + * @param {string} key + * @param {string} value * @param {number} timestamp * @return {void} */ -TimeMap.prototype.set = function(key, value, timestamp) { - if (!this.keyStore[key]) this.keyStore[key] = [] - this.keyStore[key].push([value, timestamp]) +TimeMap.prototype.set = function (key, value, timestamp) { + if (!this.keyStore[key]) this.keyStore[key] = []; + this.keyStore[key].push([value, timestamp]); }; -/** - * @param {string} key +/** + * @param {string} key * @param {number} timestamp * @return {string} */ -TimeMap.prototype.get = function(key, timestamp) { - let res = "" - const values = this.keyStore[key] || [] - let l = 0, r = values.length -1 - - while (l <= r) { - const m = Math.floor((l + r) / 2) - if (values[m][1] <= timestamp) { - res = values[m][0] - l = m + 1 - } - else r = m - 1 - } - - return res +TimeMap.prototype.get = function (key, timestamp) { + let res = ''; + const values = this.keyStore[key] || []; + let l = 0, + r = values.length - 1; + + while (l <= r) { + const m = Math.floor((l + r) / 2); + if (values[m][1] <= timestamp) { + res = values[m][0]; + l = m + 1; + } else r = m - 1; + } + + return res; }; -/** +/** * Your TimeMap object will be instantiated and called as such: * var obj = new TimeMap() * obj.set(key,value,timestamp) * var param_2 = obj.get(key,timestamp) */ - diff --git a/javascript/994-Rotting-Oranges.js b/javascript/994-Rotting-Oranges.js index 28f1d9186..831d5cf2f 100644 --- a/javascript/994-Rotting-Oranges.js +++ b/javascript/994-Rotting-Oranges.js @@ -2,39 +2,43 @@ * @param {number[][]} grid * @return {number} */ - var orangesRotting = function(grid) { - let [ROWS, COLS, time, fresh, q] = [grid.length, grid[0].length, 0, 0, []]; - let dirs = [[0,1],[0,-1],[1,0],[-1,0]]; - - // count fresh oranges and add rotten oranges to queue - for (let i=0; i < ROWS; i++){ - for ( let j=0; j < COLS; j++){ - if (grid[i][j] === 1 ) fresh++; - if (grid[i][j] === 2) q.push([i,j]) - } - } - - - while ( q.length > 0 && fresh > 0){ - let qLen = q.length; +var orangesRotting = function (grid) { + let [ROWS, COLS, time, fresh, q] = [grid.length, grid[0].length, 0, 0, []]; + let dirs = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ]; - for (let rot=0; rot < qLen; rot++){ - let [row,col] = q.shift(); + // count fresh oranges and add rotten oranges to queue + for (let i = 0; i < ROWS; i++) { + for (let j = 0; j < COLS; j++) { + if (grid[i][j] === 1) fresh++; + if (grid[i][j] === 2) q.push([i, j]); + } + } - for (let dir of dirs) { - let [r,c] = [row + dir[0], col + dir[1]]; + while (q.length > 0 && fresh > 0) { + let qLen = q.length; - if (r < 0 || r >= ROWS || c < 0 || c >= COLS || grid[r][c] !== 1) continue; + for (let rot = 0; rot < qLen; rot++) { + let [row, col] = q.shift(); - grid[r][c] = 2; - fresh--; - q.push([r,c]); + for (let dir of dirs) { + let [r, c] = [row + dir[0], col + dir[1]]; - } - } + if (r < 0 || r >= ROWS || c < 0 || c >= COLS || grid[r][c] !== 1) + continue; - time++; + grid[r][c] = 2; + fresh--; + q.push([r, c]); + } } - return fresh > 0 ? -1 : time; + time++; + } + + return fresh > 0 ? -1 : time; }; diff --git a/python/1-Two-Sum.py b/python/1-Two-Sum.py index 3eb8df064..e3eb994d3 100644 --- a/python/1-Two-Sum.py +++ b/python/1-Two-Sum.py @@ -1,7 +1,7 @@ class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: - prevMap = {} # val -> index - + prevMap = {} # val -> index + for i, n in enumerate(nums): diff = target - n if diff in prevMap: diff --git a/python/10-Regular-Expression-Matching.py b/python/10-Regular-Expression-Matching.py index b4d2a68e8..db8ad0a4c 100644 --- a/python/10-Regular-Expression-Matching.py +++ b/python/10-Regular-Expression-Matching.py @@ -3,26 +3,26 @@ class Solution: def isMatch(self, s: str, p: str) -> bool: cache = [[False] * (len(p) + 1) for i in range(len(s) + 1)] cache[len(s)][len(p)] = True - + for i in range(len(s), -1, -1): - for j in range(len(p) - 1, -1 ,-1): + for j in range(len(p) - 1, -1, -1): match = i < len(s) and (s[i] == p[j] or p[j] == ".") - + if (j + 1) < len(p) and p[j + 1] == "*": cache[i][j] = cache[i][j + 2] if match: cache[i][j] = cache[i + 1][j] or cache[i][j] elif match: - cache[i][j] = cache[i+1][j+1] - + cache[i][j] = cache[i + 1][j + 1] + return cache[0][0] - - + + # TOP DOWN MEMOIZATION class Solution: def isMatch(self, s: str, p: str) -> bool: cache = {} - + def dfs(i, j): if (i, j) in cache: return cache[(i, j)] @@ -30,16 +30,17 @@ def dfs(i, j): return True if j >= len(p): return False - + match = i < len(s) and (s[i] == p[j] or p[j] == ".") if (j + 1) < len(p) and p[j + 1] == "*": - cache[(i, j)] = (dfs(i, j + 2) or # dont use * - (match and dfs(i + 1, j))) # use * + cache[(i, j)] = dfs(i, j + 2) or ( # dont use * + match and dfs(i + 1, j) + ) # use * return cache[(i, j)] if match: - cache[(i,j)] = dfs(i + 1, j + 1) - return cache[(i,j)] - cache[(i,j)] = False + cache[(i, j)] = dfs(i + 1, j + 1) + return cache[(i, j)] + cache[(i, j)] = False return False - + return dfs(0, 0) diff --git a/python/100-Same-Tree.py b/python/100-Same-Tree.py index e054ed268..4d55e2588 100644 --- a/python/100-Same-Tree.py +++ b/python/100-Same-Tree.py @@ -5,9 +5,12 @@ # self.left = None # self.right = None + class Solution: def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: - if not p and not q: return True - if p and q and p.val == q.val: + if not p and not q: + return True + if p and q and p.val == q.val: return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) - else: return False + else: + return False diff --git a/python/102-Binary-Tree-Level-Order-Traversal.py b/python/102-Binary-Tree-Level-Order-Traversal.py index 491c1406f..6ca9a1166 100644 --- a/python/102-Binary-Tree-Level-Order-Traversal.py +++ b/python/102-Binary-Tree-Level-Order-Traversal.py @@ -5,19 +5,23 @@ # self.left = None # self.right = None + class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: res = [] q = collections.deque() - if root: q.append(root) - + if root: + q.append(root) + while q: val = [] - + for i in range(len(q)): node = q.popleft() val.append(node.val) - if node.left: q.append(node.left) - if node.right: q.append(node.right) + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) res.append(val) return res diff --git a/python/104-Maximum-Depth-of-Binary-Tree.py b/python/104-Maximum-Depth-of-Binary-Tree.py index b02eb54dc..393b2ad8d 100644 --- a/python/104-Maximum-Depth-of-Binary-Tree.py +++ b/python/104-Maximum-Depth-of-Binary-Tree.py @@ -3,34 +3,36 @@ class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 - + return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) -# ITERATIVE DFS + +# ITERATIVE DFS class Solution: def maxDepth(self, root: TreeNode) -> int: stack = [[root, 1]] res = 0 - + while stack: node, depth = stack.pop() - + if node: res = max(res, depth) stack.append([node.left, depth + 1]) stack.append([node.right, depth + 1]) return res + # BFS class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 - + level = 0 q = deque([root]) while q: - + for i in range(len(q)): node = q.popleft() if node.left: diff --git a/python/1046-Last-Stone-Weight.py b/python/1046-Last-Stone-Weight.py index e1cc3c015..ac5b574d7 100644 --- a/python/1046-Last-Stone-Weight.py +++ b/python/1046-Last-Stone-Weight.py @@ -2,12 +2,12 @@ class Solution: def lastStoneWeight(self, stones: List[int]) -> int: stones = [-s for s in stones] heapq.heapify(stones) - + while len(stones) > 1: first = heapq.heappop(stones) second = heapq.heappop(stones) if second > first: heapq.heappush(stones, first - second) - + stones.append(0) return abs(stones[0]) diff --git a/python/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.py b/python/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.py index 570d3cee5..5bb113c17 100644 --- a/python/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.py +++ b/python/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.py @@ -2,9 +2,9 @@ class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: if not preorder or not inorder: return None - + root = TreeNode(preorder[0]) mid = inorder.index(preorder[0]) - root.left = self.buildTree(preorder[1:mid + 1], inorder[:mid]) - root.right = self.buildTree(preorder[mid + 1:], inorder[mid + 1:]) + root.left = self.buildTree(preorder[1 : mid + 1], inorder[:mid]) + root.right = self.buildTree(preorder[mid + 1 :], inorder[mid + 1 :]) return root diff --git a/python/11-Container-With-Most-Water.py b/python/11-Container-With-Most-Water.py index e9607306c..339c424fe 100644 --- a/python/11-Container-With-Most-Water.py +++ b/python/11-Container-With-Most-Water.py @@ -2,7 +2,7 @@ class Solution: def maxArea(self, height: List[int]) -> int: l, r = 0, len(height) - 1 res = 0 - + while l < r: res = max(res, min(height[l], height[r]) * (r - l)) if height[l] < height[r]: diff --git a/python/110-Balanced-Binary-Tree.py b/python/110-Balanced-Binary-Tree.py index ffd200329..1cc6ec693 100644 --- a/python/110-Balanced-Binary-Tree.py +++ b/python/110-Balanced-Binary-Tree.py @@ -6,12 +6,12 @@ # self.right = right class Solution: def isBalanced(self, root: Optional[TreeNode]) -> bool: - def dfs(root): - if not root: return [True, 0] - + if not root: + return [True, 0] + left, right = dfs(root.left), dfs(root.right) - balanced = (left[0] and right[0] and - abs(left[1] - right[1]) <= 1) + balanced = left[0] and right[0] and abs(left[1] - right[1]) <= 1 return [balanced, 1 + max(left[1], right[1])] + return dfs(root)[0] diff --git a/python/1143-Longest-Common-Subsequence.py b/python/1143-Longest-Common-Subsequence.py index 77af92b4a..0860720a5 100644 --- a/python/1143-Longest-Common-Subsequence.py +++ b/python/1143-Longest-Common-Subsequence.py @@ -1,12 +1,12 @@ class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: dp = [[0 for j in range(len(text2) + 1)] for i in range(len(text1) + 1)] - + for i in range(len(text1) - 1, -1, -1): for j in range(len(text2) - 1, -1, -1): if text1[i] == text2[j]: dp[i][j] = 1 + dp[i + 1][j + 1] else: dp[i][j] = max(dp[i][j + 1], dp[i + 1][j]) - + return dp[0][0] diff --git a/python/115-Distinct-Subsequences.py b/python/115-Distinct-Subsequences.py index 67f0172fc..8f768fbfe 100644 --- a/python/115-Distinct-Subsequences.py +++ b/python/115-Distinct-Subsequences.py @@ -1,16 +1,16 @@ class Solution: def numDistinct(self, s: str, t: str) -> int: cache = {} - + for i in range(len(s) + 1): cache[(i, len(t))] = 1 for j in range(len(t)): cache[(len(s), j)] = 0 - + for i in range(len(s) - 1, -1, -1): for j in range(len(t) - 1, -1, -1): if s[i] == t[j]: - cache[(i, j)] = cache[(i+1,j+1)] + cache[(i+1,j)] + cache[(i, j)] = cache[(i + 1, j + 1)] + cache[(i + 1, j)] else: - cache[(i,j)] = cache[(i+1,j)] - return cache[(0,0)] + cache[(i, j)] = cache[(i + 1, j)] + return cache[(0, 0)] diff --git a/python/12-Integer-To-Roman.py b/python/12-Integer-To-Roman.py index 50d5393ca..f0ce9df23 100644 --- a/python/12-Integer-To-Roman.py +++ b/python/12-Integer-To-Roman.py @@ -1,13 +1,24 @@ class Solution: def intToRoman(self, num: int) -> str: - symList = [["I", 1], ["IV" , 4], ["V" , 5], ["IX" , 9], - ["X" , 10], ["XL" , 40], ["L" , 50], ["XC" , 90], - ["C" , 100], ["CD", 400], ["D", 500], ["CM", 900], - ["M" , 1000]] + symList = [ + ["I", 1], + ["IV", 4], + ["V", 5], + ["IX", 9], + ["X", 10], + ["XL", 40], + ["L", 50], + ["XC", 90], + ["C", 100], + ["CD", 400], + ["D", 500], + ["CM", 900], + ["M", 1000], + ] res = "" for sym, val in reversed(symList): if num // val: count = num // val - res += (sym * count) + res += sym * count num = num % val return res diff --git a/python/1209-Remove-All-Adjacent-Duplicates-in-String-II.py b/python/1209-Remove-All-Adjacent-Duplicates-in-String-II.py index 6fcf06bea..4356c4c28 100644 --- a/python/1209-Remove-All-Adjacent-Duplicates-in-String-II.py +++ b/python/1209-Remove-All-Adjacent-Duplicates-in-String-II.py @@ -1,18 +1,18 @@ class Solution: def removeDuplicates(self, s: str, k: int) -> str: - stack = [] # [char, count] - + stack = [] # [char, count] + for c in s: if stack and stack[-1][0] == c: stack[-1][1] += 1 else: stack.append([c, 1]) - + if stack[-1][1] == k: stack.pop() - + res = "" for char, count in stack: - res += (char * count) - + res += char * count + return res diff --git a/python/121-Best-Time-To-Buy-and-Sell-Stock.py b/python/121-Best-Time-To-Buy-and-Sell-Stock.py index 43f25e419..02bb8eb92 100644 --- a/python/121-Best-Time-To-Buy-and-Sell-Stock.py +++ b/python/121-Best-Time-To-Buy-and-Sell-Stock.py @@ -1,7 +1,7 @@ class Solution: def maxProfit(self, prices: List[int]) -> int: res = 0 - + l = 0 for r in range(1, len(prices)): if prices[r] < prices[l]: diff --git a/python/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters.py b/python/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters.py index 5c5628285..559af2295 100644 --- a/python/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters.py +++ b/python/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters.py @@ -1,7 +1,7 @@ class Solution: def maxLength(self, arr: List[str]) -> int: charSet = set() - + def overlap(charSet, s): c = Counter(charSet) + Counter(s) return max(c.values()) > 1 @@ -11,7 +11,7 @@ def overlap(charSet, s): # return True # prev.add(c) # return False - + def backtrack(i): if i == len(arr): return len(charSet) @@ -22,6 +22,6 @@ def backtrack(i): res = backtrack(i + 1) for c in arr[i]: charSet.remove(c) - return max(res, backtrack(i + 1)) # dont concatenate arr[i] - + return max(res, backtrack(i + 1)) # dont concatenate arr[i] + return backtrack(0) diff --git a/python/124-Binary-Tree-Maximum-Path-Sum.py b/python/124-Binary-Tree-Maximum-Path-Sum.py index e79190ced..b94df1d7e 100644 --- a/python/124-Binary-Tree-Maximum-Path-Sum.py +++ b/python/124-Binary-Tree-Maximum-Path-Sum.py @@ -7,20 +7,20 @@ class Solution: def maxPathSum(self, root: TreeNode) -> int: res = [root.val] - + # return max path sum without split def dfs(root): if not root: return 0 - + leftMax = dfs(root.left) rightMax = dfs(root.right) leftMax = max(leftMax, 0) rightMax = max(rightMax, 0) - + # compute max path sum WITH split res[0] = max(res[0], root.val + leftMax + rightMax) return root.val + max(leftMax, rightMax) - + dfs(root) return res[0] diff --git a/python/125-Valid-Palindrome.py b/python/125-Valid-Palindrome.py index 31723b3d7..f0e6e880e 100644 --- a/python/125-Valid-Palindrome.py +++ b/python/125-Valid-Palindrome.py @@ -2,18 +2,20 @@ class Solution: def isPalindrome(self, s: str) -> bool: l, r = 0, len(s) - 1 while l < r: - while l < r and not self.alphanum(s[l]): + while l < r and not self.alphanum(s[l]): l += 1 - while l < r and not self.alphanum(s[r]): + while l < r and not self.alphanum(s[r]): r -= 1 - if s[l].lower() != s[r].lower(): + if s[l].lower() != s[r].lower(): return False l += 1 r -= 1 return True - + # Could write own alpha-numeric function def alphanum(self, c): - return (ord('A') <= ord(c) <= ord('Z') or - ord('a') <= ord(c) <= ord('z') or - ord('0') <= ord(c) <= ord('9')) + return ( + ord("A") <= ord(c) <= ord("Z") + or ord("a") <= ord(c) <= ord("z") + or ord("0") <= ord(c) <= ord("9") + ) diff --git a/python/127-Word-Ladder.py b/python/127-Word-Ladder.py index e117b2a7b..11da720d5 100644 --- a/python/127-Word-Ladder.py +++ b/python/127-Word-Ladder.py @@ -2,14 +2,14 @@ class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: if endWord not in wordList: return 0 - + nei = collections.defaultdict(list) wordList.append(beginWord) for word in wordList: for j in range(len(word)): - pattern = word[:j] + "*" + word[j + 1:] + pattern = word[:j] + "*" + word[j + 1 :] nei[pattern].append(word) - + visit = set([beginWord]) q = deque([beginWord]) res = 1 @@ -19,7 +19,7 @@ def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int if word == endWord: return res for j in range(len(word)): - pattern = word[:j] + "*" + word[j + 1:] + pattern = word[:j] + "*" + word[j + 1 :] for neiWord in nei[pattern]: if neiWord not in visit: visit.add(neiWord) diff --git a/python/128-Longest-consecutive-sequence.py b/python/128-Longest-consecutive-sequence.py index 0c878a200..4a2168ba4 100644 --- a/python/128-Longest-consecutive-sequence.py +++ b/python/128-Longest-consecutive-sequence.py @@ -2,7 +2,7 @@ class Solution: def longestConsecutive(self, nums: List[int]) -> int: numSet = set(nums) longest = 0 - + for n in nums: # check if its the start of a sequence if (n - 1) not in numSet: @@ -11,4 +11,3 @@ def longestConsecutive(self, nums: List[int]) -> int: length += 1 longest = max(length, longest) return longest - diff --git a/python/13-Roman-To-Integer.py b/python/13-Roman-To-Integer.py index 3bd3a2abb..8aa9543c1 100644 --- a/python/13-Roman-To-Integer.py +++ b/python/13-Roman-To-Integer.py @@ -1,7 +1,6 @@ class Solution: def romanToInt(self, s: str) -> int: - roman = { "I" : 1, "V" : 5, "X" : 10, - "L" : 50, "C" : 100, "D" : 500, "M" : 1000 } + roman = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} res = 0 for i in range(len(s)): if i + 1 < len(s) and roman[s[i]] < roman[s[i + 1]]: diff --git a/python/130-Surrounded-Regions.py b/python/130-Surrounded-Regions.py index dfbb8308a..a27984aad 100644 --- a/python/130-Surrounded-Regions.py +++ b/python/130-Surrounded-Regions.py @@ -1,30 +1,28 @@ class Solution: def solve(self, board: List[List[str]]) -> None: ROWS, COLS = len(board), len(board[0]) - + def capture(r, c): - if (r < 0 or c < 0 or r == ROWS or c == COLS - or board[r][c] != "O"): + if r < 0 or c < 0 or r == ROWS or c == COLS or board[r][c] != "O": return board[r][c] = "T" capture(r + 1, c) capture(r - 1, c) capture(r, c + 1) capture(r, c - 1) - + # 1. (DFS) Capture unsurrounded regions (O -> T) for r in range(ROWS): for c in range(COLS): - if (board[r][c] == "O" and - (r in [0, ROWS - 1] or c in [0, COLS - 1])): + if board[r][c] == "O" and (r in [0, ROWS - 1] or c in [0, COLS - 1]): capture(r, c) - + # 2. Capture surrounded regions (O -> X) for r in range(ROWS): for c in range(COLS): if board[r][c] == "O": board[r][c] = "X" - + # 3. Uncapture unsurrounded regions (T -> O) for r in range(ROWS): for c in range(COLS): diff --git a/python/131-Palindrome-Partitioning.py b/python/131-Palindrome-Partitioning.py index 21df07917..f0893bbcb 100644 --- a/python/131-Palindrome-Partitioning.py +++ b/python/131-Palindrome-Partitioning.py @@ -1,19 +1,20 @@ class Solution: def partition(self, s: str) -> List[List[str]]: res, part = [], [] - + def dfs(i): if i >= len(s): res.append(part.copy()) return for j in range(i, len(s)): if self.isPali(s, i, j): - part.append(s[i:j+1]) + part.append(s[i : j + 1]) dfs(j + 1) part.pop() + dfs(0) return res - + def isPali(self, s, l, r): while l < r: if s[l] != s[r]: diff --git a/python/133-Clone-Graph.py b/python/133-Clone-Graph.py index 36505a209..704c8e8a4 100644 --- a/python/133-Clone-Graph.py +++ b/python/133-Clone-Graph.py @@ -1,15 +1,15 @@ class Solution: - def cloneGraph(self, node: 'Node') -> 'Node': + def cloneGraph(self, node: "Node") -> "Node": oldToNew = {} - + def dfs(node): if node in oldToNew: return oldToNew[node] - + copy = Node(node.val) oldToNew[node] = copy for nei in node.neighbors: copy.neighbors.append(dfs(nei)) return copy - + return dfs(node) if node else None diff --git a/python/134-Gas-Station.py b/python/134-Gas-Station.py index 2e90d2a7b..a33d8e773 100644 --- a/python/134-Gas-Station.py +++ b/python/134-Gas-Station.py @@ -1,14 +1,14 @@ class Solution: - def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: + def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: start, end = len(gas) - 1, 0 total = gas[start] - cost[start] - + while start >= end: while total < 0 and start >= end: start -= 1 - total += (gas[start] - cost[start]) + total += gas[start] - cost[start] if start == end: - return start - total += (gas[end] - cost[end]) + return start + total += gas[end] - cost[end] end += 1 return -1 diff --git a/python/138-Copy-List-With-Random-Pointer.py b/python/138-Copy-List-With-Random-Pointer.py index 386fd1a41..9942e9ede 100644 --- a/python/138-Copy-List-With-Random-Pointer.py +++ b/python/138-Copy-List-With-Random-Pointer.py @@ -7,10 +7,11 @@ def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.random = random """ + class Solution: - def copyRandomList(self, head: 'Node') -> 'Node': - oldToCopy = { None : None } - + def copyRandomList(self, head: "Node") -> "Node": + oldToCopy = {None: None} + cur = head while cur: copy = Node(cur.val) diff --git a/python/139-Word-Break.py b/python/139-Word-Break.py index ae5d2e972..681107bd2 100644 --- a/python/139-Word-Break.py +++ b/python/139-Word-Break.py @@ -1,14 +1,14 @@ class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: - + dp = [False] * (len(s) + 1) dp[len(s)] = True - + for i in range(len(s) - 1, -1, -1): for w in wordDict: if (i + len(w)) <= len(s) and s[i : i + len(w)] == w: dp[i] = dp[i + len(w)] if dp[i]: break - + return dp[0] diff --git a/python/141-Linked-List-Cycle.py b/python/141-Linked-List-Cycle.py index 6758f32a4..1fcb83888 100644 --- a/python/141-Linked-List-Cycle.py +++ b/python/141-Linked-List-Cycle.py @@ -4,10 +4,11 @@ # self.val = x # self.next = None + class Solution: def hasCycle(self, head: ListNode) -> bool: slow, fast = head, head - + while fast and fast.next: slow = slow.next fast = fast.next.next diff --git a/python/143-Reorder-List.py b/python/143-Reorder-List.py index 9b210b7c6..899ae98a0 100644 --- a/python/143-Reorder-List.py +++ b/python/143-Reorder-List.py @@ -5,7 +5,7 @@ def reorderList(self, head: ListNode) -> None: while fast and fast.next: slow = slow.next fast = fast.next.next - + # reverse second half second = slow.next prev = slow.next = None @@ -14,7 +14,7 @@ def reorderList(self, head: ListNode) -> None: second.next = prev prev = second second = tmp - + # merge two halfs first, second = head, prev while second: diff --git a/python/1448-Count-Good-Nodes-in-Binary-Tree.py b/python/1448-Count-Good-Nodes-in-Binary-Tree.py index 6b3325122..4fce28f4e 100644 --- a/python/1448-Count-Good-Nodes-in-Binary-Tree.py +++ b/python/1448-Count-Good-Nodes-in-Binary-Tree.py @@ -6,15 +6,14 @@ # self.right = right class Solution: def goodNodes(self, root: TreeNode) -> int: - def dfs(node, maxVal): if not node: return 0 - + res = 1 if node.val >= maxVal else 0 maxVal = max(maxVal, node.val) res += dfs(node.left, maxVal) res += dfs(node.right, maxVal) return res - + return dfs(root, root.val) diff --git a/python/146-LRU-Cache.py b/python/146-LRU-Cache.py index cd06aed11..effa83d6f 100644 --- a/python/146-LRU-Cache.py +++ b/python/146-LRU-Cache.py @@ -2,13 +2,13 @@ class Node: def __init__(self, key, val): self.key, self.val = key, val self.prev = self.next = None - -class LRUCache: + +class LRUCache: def __init__(self, capacity: int): self.cap = capacity - self.cache = {} # map key to node - + self.cache = {} # map key to node + self.left, self.right = Node(0, 0), Node(0, 0) self.left.next, self.right.prev = self.right, self.left @@ -16,26 +16,26 @@ def __init__(self, capacity: int): def remove(self, node): prev, nxt = node.prev, node.next prev.next, nxt.prev = nxt, prev - + # insert node at right def insert(self, node): prev, nxt = self.right.prev, self.right prev.next = nxt.prev = node node.next, node.prev = nxt, prev - + def get(self, key: int) -> int: if key in self.cache: self.remove(self.cache[key]) self.insert(self.cache[key]) return self.cache[key].val return -1 - + def put(self, key: int, value: int) -> None: if key in self.cache: self.remove(self.cache[key]) self.cache[key] = Node(key, value) self.insert(self.cache[key]) - + if len(self.cache) > self.cap: # remove from the list and delete the LRU from hashmap lru = self.left.next diff --git a/python/15-3Sum.py b/python/15-3Sum.py index e8e256717..36719ec35 100644 --- a/python/15-3Sum.py +++ b/python/15-3Sum.py @@ -2,11 +2,11 @@ class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: res = [] nums.sort() - + for i, a in enumerate(nums): if i > 0 and a == nums[i - 1]: continue - + l, r = i + 1, len(nums) - 1 while l < r: threeSum = a + nums[l] + nums[r] diff --git a/python/152-Maximum-Product-Subarray.py b/python/152-Maximum-Product-Subarray.py index 5297e1fbe..93f00e256 100644 --- a/python/152-Maximum-Product-Subarray.py +++ b/python/152-Maximum-Product-Subarray.py @@ -3,11 +3,11 @@ def maxProduct(self, nums: List[int]) -> int: # O(n)/O(1) : Time/Memory res = max(nums) curMin, curMax = 1, 1 - + for n in nums: - + tmp = curMax * n - curMax = max(n * curMax, n * curMin, n) + curMax = max(n * curMax, n * curMin, n) curMin = min(tmp, n * curMin, n) res = max(res, curMax) return res diff --git a/python/153-Find-Minimum-in-Rotated-Sorted-Array.py b/python/153-Find-Minimum-in-Rotated-Sorted-Array.py index 8b4caf773..e36c53238 100644 --- a/python/153-Find-Minimum-in-Rotated-Sorted-Array.py +++ b/python/153-Find-Minimum-in-Rotated-Sorted-Array.py @@ -2,7 +2,7 @@ class Solution: def findMin(self, nums: List[int]) -> int: res = nums[0] l, r = 0, len(nums) - 1 - + while l <= r: if nums[l] < nums[r]: res = min(res, nums[l]) diff --git a/python/155-Min-Stack.py b/python/155-Min-Stack.py index f0789b4c4..798e3ca63 100644 --- a/python/155-Min-Stack.py +++ b/python/155-Min-Stack.py @@ -1,9 +1,8 @@ class MinStack: - def __init__(self): self.stack = [] self.minStack = [] - + def push(self, val: int) -> None: self.stack.append(val) val = min(val, self.minStack[-1] if self.minStack else val) diff --git a/python/1584-Min-Cost-to-Connect-all-Points.py b/python/1584-Min-Cost-to-Connect-all-Points.py index 4126570f7..0ad2e2fc0 100644 --- a/python/1584-Min-Cost-to-Connect-all-Points.py +++ b/python/1584-Min-Cost-to-Connect-all-Points.py @@ -1,7 +1,7 @@ class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: N = len(points) - adj = { i:[] for i in range(N) } # i : list of [cost, node] + adj = {i: [] for i in range(N)} # i : list of [cost, node] for i in range(N): x1, y1 = points[i] for j in range(i + 1, N): @@ -9,11 +9,11 @@ def minCostConnectPoints(self, points: List[List[int]]) -> int: dist = abs(x1 - x2) + abs(y1 - y2) adj[i].append([dist, j]) adj[j].append([dist, i]) - + # Prim's res = 0 visit = set() - minH = [[0, 0]] # [cost, point] + minH = [[0, 0]] # [cost, point] while len(visit) < N: cost, i = heapq.heappop(minH) if i in visit: diff --git a/python/160-Intersection-of-Two-Linked-Lists.py b/python/160-Intersection-of-Two-Linked-Lists.py index d11c79f2f..2d4422f20 100644 --- a/python/160-Intersection-of-Two-Linked-Lists.py +++ b/python/160-Intersection-of-Two-Linked-Lists.py @@ -4,9 +4,12 @@ # self.val = x # self.next = None + class Solution: - def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: - l1, l2 = headA, headB + def getIntersectionNode( + self, headA: ListNode, headB: ListNode + ) -> Optional[ListNode]: + l1, l2 = headA, headB while l1 != l2: l1 = l1.next if l1 else headB l2 = l2.next if l2 else headA diff --git a/python/167-Two-Sum-II.py b/python/167-Two-Sum-II.py index 47ae0adde..886210f44 100644 --- a/python/167-Two-Sum-II.py +++ b/python/167-Two-Sum-II.py @@ -1,13 +1,13 @@ class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: l, r = 0, len(numbers) - 1 - + while l < r: curSum = numbers[l] + numbers[r] - + if curSum > target: r -= 1 elif curSum < target: l += 1 else: - return [l + 1, r + 1] + return [l + 1, r + 1] diff --git a/python/17-Letter-Combinations-of-a-Phone-Number.py b/python/17-Letter-Combinations-of-a-Phone-Number.py index 515bf7247..22ebf9a03 100644 --- a/python/17-Letter-Combinations-of-a-Phone-Number.py +++ b/python/17-Letter-Combinations-of-a-Phone-Number.py @@ -1,23 +1,25 @@ class Solution: def letterCombinations(self, digits: str) -> List[str]: res = [] - digitToChar = { "2": "abc", - "3": "def", - "4": "ghi", - "5": "jkl", - "6": "mno", - "7": "qprs", - "8": "tuv", - "9": "wxyz" } - + digitToChar = { + "2": "abc", + "3": "def", + "4": "ghi", + "5": "jkl", + "6": "mno", + "7": "qprs", + "8": "tuv", + "9": "wxyz", + } + def backtrack(i, curStr): if len(curStr) == len(digits): res.append(curStr) return for c in digitToChar[digits[i]]: backtrack(i + 1, curStr + c) - + if digits: backtrack(0, "") - + return res diff --git a/python/1851-Minimum-Interval-to-Include-Each-Query.py b/python/1851-Minimum-Interval-to-Include-Each-Query.py index d10ffe14a..545cefaa2 100644 --- a/python/1851-Minimum-Interval-to-Include-Each-Query.py +++ b/python/1851-Minimum-Interval-to-Include-Each-Query.py @@ -9,7 +9,7 @@ def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[in l, r = intervals[i] heapq.heappush(minHeap, (r - l + 1, r)) i += 1 - + while minHeap and minHeap[0][1] < q: heapq.heappop(minHeap) res[q] = minHeap[0][0] if minHeap else -1 diff --git a/python/1899-Merge-Triplets-to-Form-Target-Triplet.py b/python/1899-Merge-Triplets-to-Form-Target-Triplet.py index 170563995..830803939 100644 --- a/python/1899-Merge-Triplets-to-Form-Target-Triplet.py +++ b/python/1899-Merge-Triplets-to-Form-Target-Triplet.py @@ -1,7 +1,7 @@ class Solution: def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool: good = set() - + for t in triplets: if t[0] > target[0] or t[1] > target[1] or t[2] > target[2]: continue diff --git a/python/19-Remove-Nth-node-from-end-of-List.py b/python/19-Remove-Nth-node-from-end-of-List.py index 09c5b9f11..0013f1db2 100644 --- a/python/19-Remove-Nth-node-from-end-of-List.py +++ b/python/19-Remove-Nth-node-from-end-of-List.py @@ -3,15 +3,15 @@ def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: dummy = ListNode(0, head) left = dummy right = head - + while n > 0: right = right.next n -= 1 - + while right: left = left.next right = right.next - + # delete left.next = left.next.next return dummy.next diff --git a/python/1905-Count-Sub-Islands.py b/python/1905-Count-Sub-Islands.py index ed0ddea98..4cb0b42e9 100644 --- a/python/1905-Count-Sub-Islands.py +++ b/python/1905-Count-Sub-Islands.py @@ -2,23 +2,29 @@ class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: ROWS, COLS = len(grid1), len(grid1[0]) visit = set() - + def dfs(r, c): - if (r < 0 or c < 0 or r == ROWS or c == COLS or - grid2[r][c] == 0 or (r, c) in visit): + if ( + r < 0 + or c < 0 + or r == ROWS + or c == COLS + or grid2[r][c] == 0 + or (r, c) in visit + ): return True - + visit.add((r, c)) res = True if grid1[r][c] == 0: res = False - + res = dfs(r - 1, c) and res res = dfs(r + 1, c) and res res = dfs(r, c - 1) and res res = dfs(r, c + 1) and res return res - + count = 0 for r in range(ROWS): for c in range(COLS): diff --git a/python/191-Number-of-1-Bits.py b/python/191-Number-of-1-Bits.py index 9a61e7784..9a311cfa2 100644 --- a/python/191-Number-of-1-Bits.py +++ b/python/191-Number-of-1-Bits.py @@ -2,6 +2,6 @@ class Solution: def hammingWeight(self, n: int) -> int: res = 0 while n: - n &= (n - 1) + n &= n - 1 res += 1 return res diff --git a/python/198-House-Robber.py b/python/198-House-Robber.py index d6f380340..512f67aea 100644 --- a/python/198-House-Robber.py +++ b/python/198-House-Robber.py @@ -1,7 +1,7 @@ class Solution: def rob(self, nums: List[int]) -> int: rob1, rob2 = 0, 0 - + for n in nums: temp = max(n + rob1, rob2) rob1 = rob2 diff --git a/python/199-Binary-Tree-Right-Side-View.py b/python/199-Binary-Tree-Right-Side-View.py index 11040e880..b027c7519 100644 --- a/python/199-Binary-Tree-Right-Side-View.py +++ b/python/199-Binary-Tree-Right-Side-View.py @@ -8,11 +8,11 @@ class Solution: def rightSideView(self, root: TreeNode) -> List[int]: res = [] q = collections.deque([root]) - + while q: rightSide = None qLen = len(q) - + for i in range(qLen): node = q.popleft() if node: @@ -20,5 +20,5 @@ def rightSideView(self, root: TreeNode) -> List[int]: q.append(node.left) q.append(node.right) if rightSide: - res.append(rightSide.val) + res.append(rightSide.val) return res diff --git a/python/2-Add-Two-Numbers.py b/python/2-Add-Two-Numbers.py index 63f6ed14a..01d754c99 100644 --- a/python/2-Add-Two-Numbers.py +++ b/python/2-Add-Two-Numbers.py @@ -7,18 +7,18 @@ class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: dummy = ListNode() cur = dummy - + carry = 0 while l1 or l2 or carry: v1 = l1.val if l1 else 0 v2 = l2.val if l2 else 0 - + # new digit val = v1 + v2 + carry carry = val // 10 val = val % 10 cur.next = ListNode(val) - + # update ptrs cur = cur.next l1 = l1.next if l1 else None diff --git a/python/20-Valid-Parentheses.py b/python/20-Valid-Parentheses.py index 6bb09f9a7..4d0ae3424 100644 --- a/python/20-Valid-Parentheses.py +++ b/python/20-Valid-Parentheses.py @@ -1,14 +1,14 @@ class Solution: def isValid(self, s: str) -> bool: - Map = { ")":"(", "]":"[", "}":"{" } + Map = {")": "(", "]": "[", "}": "{"} stack = [] - + for c in s: if c not in Map: stack.append(c) - continue + continue if not stack or stack[-1] != Map[c]: return False stack.pop() - + return not stack diff --git a/python/200-Number-of-Islands.py b/python/200-Number-of-Islands.py index 8c707742b..53204e67e 100644 --- a/python/200-Number-of-Islands.py +++ b/python/200-Number-of-Islands.py @@ -2,23 +2,25 @@ class Solution: def numIslands(self, grid: List[List[str]]) -> int: if not grid or not grid[0]: return 0 - + islands = 0 visit = set() rows, cols = len(grid), len(grid[0]) - + def dfs(r, c): - if (r not in range(rows) or - c not in range(cols) or - grid[r][c] == "0" or - (r, c) in visit): + if ( + r not in range(rows) + or c not in range(cols) + or grid[r][c] == "0" + or (r, c) in visit + ): return - + visit.add((r, c)) directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] for dr, dc in directions: dfs(r + dr, c + dc) - + for r in range(rows): for c in range(cols): if grid[r][c] == "1" and (r, c) not in visit: diff --git a/python/2013-Detect-Squares.py b/python/2013-Detect-Squares.py index 82f16dc9b..8230830d2 100644 --- a/python/2013-Detect-Squares.py +++ b/python/2013-Detect-Squares.py @@ -1,6 +1,4 @@ - class DetectSquares: - def __init__(self): self.ptsCount = defaultdict(int) self.pts = [] @@ -8,11 +6,11 @@ def __init__(self): def add(self, point: List[int]) -> None: self.ptsCount[tuple(point)] += 1 self.pts.append(point) - + def count(self, point: List[int]) -> int: res = 0 px, py = point - for x, y in self.pts: + for x, y in self.pts: if (abs(py - y) != abs(px - x)) or x == px or y == py: continue res += self.ptsCount[(x, py)] * self.ptsCount[(px, y)] diff --git a/python/202-Happy-Number.py b/python/202-Happy-Number.py index 3264c91d3..f220816c9 100644 --- a/python/202-Happy-Number.py +++ b/python/202-Happy-Number.py @@ -1,14 +1,14 @@ class Solution: def isHappy(self, n: int) -> bool: slow, fast = n, self.sumSquareDigits(n) - + while slow != fast: fast = self.sumSquareDigits(fast) fast = self.sumSquareDigits(fast) slow = self.sumSquareDigits(slow) return True if fast == 1 else False - + def sumSquareDigits(self, n): output = 0 while n: diff --git a/python/206-Reverse-Linked-List.py b/python/206-Reverse-Linked-List.py index a1f36aeee..f49146d53 100644 --- a/python/206-Reverse-Linked-List.py +++ b/python/206-Reverse-Linked-List.py @@ -4,11 +4,12 @@ # self.val = x # self.next = None + class Solution: def reverseList(self, head: ListNode) -> ListNode: prev, curr = None, head - - while curr: + + while curr: temp = curr.next curr.next = prev prev = curr diff --git a/python/207-Course-Schedule.py b/python/207-Course-Schedule.py index 26f56d773..e52ea99e3 100644 --- a/python/207-Course-Schedule.py +++ b/python/207-Course-Schedule.py @@ -1,26 +1,29 @@ class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: # dfs - preMap = { i:[] for i in range(numCourses)} - + preMap = {i: [] for i in range(numCourses)} + # map each course to : prereq list for crs, pre in prerequisites: preMap[crs].append(pre) - + visiting = set() + def dfs(crs): if crs in visiting: return False if preMap[crs] == []: return True - + visiting.add(crs) for pre in preMap[crs]: - if not dfs(pre): return False + if not dfs(pre): + return False visiting.remove(crs) preMap[crs] = [] return True - + for c in range(numCourses): - if not dfs(c): return False + if not dfs(c): + return False return True diff --git a/python/208-Implement-Trie.py b/python/208-Implement-Trie.py index 8ab6ec933..fc26daebf 100644 --- a/python/208-Implement-Trie.py +++ b/python/208-Implement-Trie.py @@ -2,15 +2,14 @@ class TrieNode: def __init__(self): self.children = [None] * 26 self.end = False - + + class Trie: - def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() - def insert(self, word: str) -> None: """ @@ -18,19 +17,19 @@ def insert(self, word: str) -> None: """ curr = self.root for c in word: - i = ord(c)-ord("a") + i = ord(c) - ord("a") if curr.children[i] == None: curr.children[i] = TrieNode() curr = curr.children[i] curr.end = True - + def search(self, word: str) -> bool: """ Returns if the word is in the trie. """ curr = self.root for c in word: - i = ord(c)-ord("a") + i = ord(c) - ord("a") if curr.children[i] == None: return False curr = curr.children[i] @@ -42,7 +41,7 @@ def startsWith(self, prefix: str) -> bool: """ curr = self.root for c in prefix: - i = ord(c)-ord("a") + i = ord(c) - ord("a") if curr.children[i] == None: return False curr = curr.children[i] diff --git a/python/21-Merge-Two-Sorted-Lists.py b/python/21-Merge-Two-Sorted-Lists.py index eb69a1c41..9a4fa31a2 100644 --- a/python/21-Merge-Two-Sorted-Lists.py +++ b/python/21-Merge-Two-Sorted-Lists.py @@ -7,7 +7,7 @@ class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: dummy = ListNode() tail = dummy - + while l1 and l2: if l1.val < l2.val: tail.next = l1 @@ -16,10 +16,10 @@ def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: tail.next = l2 l2 = l2.next tail = tail.next - + if l1: tail.next = l1 elif l2: tail.next = l2 - + return dummy.next diff --git a/python/210-Course-Schedule-II.py b/python/210-Course-Schedule-II.py index 5c52edf67..8c59b6e1e 100644 --- a/python/210-Course-Schedule-II.py +++ b/python/210-Course-Schedule-II.py @@ -1,17 +1,18 @@ class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: - prereq = { c:[] for c in range(numCourses) } + prereq = {c: [] for c in range(numCourses)} for crs, pre in prerequisites: prereq[crs].append(pre) - + output = [] visit, cycle = set(), set() + def dfs(crs): if crs in cycle: return False if crs in visit: return True - + cycle.add(crs) for pre in prereq[crs]: if dfs(pre) == False: @@ -20,8 +21,8 @@ def dfs(crs): visit.add(crs) output.append(crs) return True - + for c in range(numCourses): if dfs(c) == False: - return [] + return [] return output diff --git a/python/211-Design-Add-and-Search-Words-Data-Structure.py b/python/211-Design-Add-and-Search-Words-Data-Structure.py index a55cb042e..3c5f562aa 100644 --- a/python/211-Design-Add-and-Search-Words-Data-Structure.py +++ b/python/211-Design-Add-and-Search-Words-Data-Structure.py @@ -1,12 +1,13 @@ class TrieNode: def __init__(self): - self.children = {} # a : TrieNode + self.children = {} # a : TrieNode self.word = False + class WordDictionary: def __init__(self): self.root = TrieNode() - + def addWord(self, word: str) -> None: cur = self.root for c in word: @@ -14,7 +15,7 @@ def addWord(self, word: str) -> None: cur.children[c] = TrieNode() cur = cur.children[c] cur.word = True - + def search(self, word: str) -> bool: def dfs(j, root): cur = root @@ -31,5 +32,5 @@ def dfs(j, root): return False cur = cur.children[c] return cur.word - + return dfs(0, self.root) diff --git a/python/212-Word-Search-II.py b/python/212-Word-Search-II.py index 0da4c8cb0..eded5b9b4 100644 --- a/python/212-Word-Search-II.py +++ b/python/212-Word-Search-II.py @@ -3,7 +3,7 @@ def __init__(self): self.children = {} self.isWord = False self.refs = 0 - + def addWord(self, word): cur = self cur.refs += 1 @@ -13,7 +13,7 @@ def addWord(self, word): cur = cur.children[c] cur.refs += 1 cur.isWord = True - + def removeWord(self, word): cur = self cur.refs -= 1 @@ -22,24 +22,28 @@ def removeWord(self, word): cur = cur.children[c] cur.refs -= 1 - + class Solution: def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: root = TrieNode() for w in words: root.addWord(w) - + ROWS, COLS = len(board), len(board[0]) res, visit = set(), set() - + def dfs(r, c, node, word): - if (r < 0 or c < 0 or - r == ROWS or c == COLS or - board[r][c] not in node.children or - node.children[board[r][c]].refs < 1 or - (r, c) in visit): + if ( + r < 0 + or c < 0 + or r == ROWS + or c == COLS + or board[r][c] not in node.children + or node.children[board[r][c]].refs < 1 + or (r, c) in visit + ): return - + visit.add((r, c)) node = node.children[board[r][c]] word += board[r][c] @@ -47,15 +51,15 @@ def dfs(r, c, node, word): node.isWord = False res.add(word) root.removeWord(word) - + dfs(r + 1, c, node, word) dfs(r - 1, c, node, word) dfs(r, c + 1, node, word) dfs(r, c - 1, node, word) visit.remove((r, c)) - + for r in range(ROWS): for c in range(COLS): dfs(r, c, root, "") - + return list(res) diff --git a/python/213-House-Robber-II.py b/python/213-House-Robber-II.py index e03cef8ac..ad7fdf484 100644 --- a/python/213-House-Robber-II.py +++ b/python/213-House-Robber-II.py @@ -1,10 +1,10 @@ class Solution: def rob(self, nums: List[int]) -> int: return max(nums[0], self.helper(nums[1:]), self.helper(nums[:-1])) - + def helper(self, nums): rob1, rob2 = 0, 0 - + for n in nums: newRob = max(rob1 + n, rob2) rob1 = rob2 diff --git a/python/215-Kth-Largest-Element-in-an-Array.py b/python/215-Kth-Largest-Element-in-an-Array.py index 58221e21a..910a1db38 100644 --- a/python/215-Kth-Largest-Element-in-an-Array.py +++ b/python/215-Kth-Largest-Element-in-an-Array.py @@ -2,19 +2,25 @@ class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: nums.sort() return nums[len(nums) - k] - + k = len(nums) - k + def quickSelect(l, r): - if l == r: return nums[l] - + if l == r: + return nums[l] + pivot, p = nums[r], l for i in range(l, r): if nums[i] <= pivot: nums[p], nums[i] = nums[i], nums[p] p += 1 nums[p], nums[r] = nums[r], nums[p] - - if p > k: return quickSelect(l, p - 1) - elif p < k: return quickSelect(p + 1, r) - else: return nums[p] + + if p > k: + return quickSelect(l, p - 1) + elif p < k: + return quickSelect(p + 1, r) + else: + return nums[p] + return quickSelect(0, len(nums) - 1) diff --git a/python/217-Contains-Duplicate.py b/python/217-Contains-Duplicate.py index 344305a26..9ec8f05a9 100644 --- a/python/217-Contains-Duplicate.py +++ b/python/217-Contains-Duplicate.py @@ -1,7 +1,7 @@ class Solution: def containsDuplicate(self, nums: List[int]) -> bool: hashset = set() - + for n in nums: if n in hashset: return True diff --git a/python/22-Generate-Parentheses.py b/python/22-Generate-Parentheses.py index 82e2e7e26..879e66738 100644 --- a/python/22-Generate-Parentheses.py +++ b/python/22-Generate-Parentheses.py @@ -2,12 +2,12 @@ class Solution: def generateParenthesis(self, n: int) -> List[str]: stack = [] res = [] - + def backtrack(openN, closedN): if openN == closedN == n: res.append("".join(stack)) return - + if openN < n: stack.append("(") backtrack(openN + 1, closedN) @@ -16,6 +16,6 @@ def backtrack(openN, closedN): stack.append(")") backtrack(openN, closedN + 1) stack.pop() - + backtrack(0, 0) return res diff --git a/python/221-Maximal-Square.py b/python/221-Maximal-Square.py index 944b21965..14c13d055 100644 --- a/python/221-Maximal-Square.py +++ b/python/221-Maximal-Square.py @@ -1,20 +1,21 @@ class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: ROWS, COLS = len(matrix), len(matrix[0]) - cache = {} # map each (r, c) -> maxLength of square - + cache = {} # map each (r, c) -> maxLength of square + def helper(r, c): if r >= ROWS or c >= COLS: return 0 - + if (r, c) not in cache: down = helper(r + 1, c) right = helper(r, c + 1) diag = helper(r + 1, c + 1) - + cache[(r, c)] = 0 if matrix[r][c] == "1": cache[(r, c)] = 1 + min(down, right, diag) return cache[(r, c)] + helper(0, 0) return max(cache.values()) ** 2 diff --git a/python/226-Invert-Binary-Tree.py b/python/226-Invert-Binary-Tree.py index 36de77ef4..71740bd12 100644 --- a/python/226-Invert-Binary-Tree.py +++ b/python/226-Invert-Binary-Tree.py @@ -8,12 +8,12 @@ class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root: return None - + # swap the children tmp = root.left root.left = root.right root.right = tmp - + self.invertTree(root.left) self.invertTree(root.right) return root diff --git a/python/23-Merge-K-Sorted-Lists.py b/python/23-Merge-K-Sorted-Lists.py index 54cabf592..4613f0235 100644 --- a/python/23-Merge-K-Sorted-Lists.py +++ b/python/23-Merge-K-Sorted-Lists.py @@ -7,7 +7,7 @@ class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: if not lists or len(lists) == 0: return None - + while len(lists) > 1: mergedLists = [] for i in range(0, len(lists), 2): @@ -16,11 +16,11 @@ def mergeKLists(self, lists: List[ListNode]) -> ListNode: mergedLists.append(self.mergeList(l1, l2)) lists = mergedLists return lists[0] - + def mergeList(self, l1, l2): dummy = ListNode() tail = dummy - + while l1 and l2: if l1.val < l2.val: tail.next = l1 diff --git a/python/230-Kth-Smallest-Element-in-a-BST.py b/python/230-Kth-Smallest-Element-in-a-BST.py index f79a0be6d..15f6dde4e 100644 --- a/python/230-Kth-Smallest-Element-in-a-BST.py +++ b/python/230-Kth-Smallest-Element-in-a-BST.py @@ -5,11 +5,12 @@ # self.left = None # self.right = None + class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: stack = [] curr = root - + while stack or curr: while curr: stack.append(curr) diff --git a/python/236-Lowest-Common-Ancestor-of-a-Binary-Tree.py b/python/236-Lowest-Common-Ancestor-of-a-Binary-Tree.py index 1c33c28b0..06131f4f6 100644 --- a/python/236-Lowest-Common-Ancestor-of-a-Binary-Tree.py +++ b/python/236-Lowest-Common-Ancestor-of-a-Binary-Tree.py @@ -5,17 +5,23 @@ # self.left = None # self.right = None + class Solution: res = None - def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': - if not root or not p or not q: return None - + + def lowestCommonAncestor( + self, root: "TreeNode", p: "TreeNode", q: "TreeNode" + ) -> "TreeNode": + if not root or not p or not q: + return None + def search(root, p, q): - if not root: return False + if not root: + return False mid = left = right = False - if root.val == p.val or root.val == q.val: + if root.val == p.val or root.val == q.val: mid = True - + left = search(root.left, p, q) right = search(root.right, p, q) if mid: @@ -24,6 +30,6 @@ def search(root, p, q): elif left and right: self.res = root return mid or left or right - + search(root, p, q) return self.res diff --git a/python/238-Product-of-array-except-self.py b/python/238-Product-of-array-except-self.py index 77ccdf892..0326913a3 100644 --- a/python/238-Product-of-array-except-self.py +++ b/python/238-Product-of-array-except-self.py @@ -1,7 +1,7 @@ class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: res = [1] * (len(nums)) - + prefix = 1 for i in range(len(nums)): res[i] = prefix @@ -11,4 +11,3 @@ def productExceptSelf(self, nums: List[int]) -> List[int]: res[i] *= postfix postfix *= nums[i] return res - diff --git a/python/239-Sliding-Window-Maximum.py b/python/239-Sliding-Window-Maximum.py index d78266eb6..3327ca5f4 100644 --- a/python/239-Sliding-Window-Maximum.py +++ b/python/239-Sliding-Window-Maximum.py @@ -2,7 +2,7 @@ class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: indexQ = deque() valQ = deque() - + res = [] for i, n in enumerate(nums): while valQ and n > valQ[-1]: @@ -10,7 +10,7 @@ def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: indexQ.pop() valQ.append(n) indexQ.append(i) - + while i - indexQ[0] + 1 > k: valQ.popleft() indexQ.popleft() diff --git a/python/24-Swap-Nodes-in-Pairs.py b/python/24-Swap-Nodes-in-Pairs.py index 5781a78f3..19fb28cce 100644 --- a/python/24-Swap-Nodes-in-Pairs.py +++ b/python/24-Swap-Nodes-in-Pairs.py @@ -7,19 +7,19 @@ class Solution: def swapPairs(self, head: ListNode) -> ListNode: dummy = ListNode(0, head) prev, curr = dummy, head - + while curr and curr.next: # save ptrs nxtPair = curr.next.next second = curr.next - + # reverse this pair second.next = curr curr.next = nxtPair prev.next = second - + # update ptrs prev = curr curr = nxtPair - + return dummy.next diff --git a/python/242-Valid-Anagrams.py b/python/242-Valid-Anagrams.py index 62411b729..ad374a605 100644 --- a/python/242-Valid-Anagrams.py +++ b/python/242-Valid-Anagrams.py @@ -2,9 +2,9 @@ class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False - + countS, countT = {}, {} - + for i in range(len(s)): countS[s[i]] = 1 + countS.get(s[i], 0) countT[t[i]] = 1 + countT.get(t[i], 0) diff --git a/python/25-Reverse-Nodes-in-K-Group.py b/python/25-Reverse-Nodes-in-K-Group.py index 0add4f17d..43d9d5879 100644 --- a/python/25-Reverse-Nodes-in-K-Group.py +++ b/python/25-Reverse-Nodes-in-K-Group.py @@ -2,13 +2,13 @@ class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: dummy = ListNode(0, head) groupPrev = dummy - + while True: kth = self.getKth(groupPrev, k) if not kth: break groupNext = kth.next - + # reverse group prev, curr = kth.next, groupPrev.next while curr != groupNext: @@ -16,12 +16,12 @@ def reverseKGroup(self, head: ListNode, k: int) -> ListNode: curr.next = prev prev = curr curr = tmp - + tmp = groupPrev.next groupPrev.next = kth groupPrev = tmp - return dummy.next - + return dummy.next + def getKth(self, curr, k): while curr and k > 0: curr = curr.next diff --git a/python/252-Meeting-Rooms.py b/python/252-Meeting-Rooms.py index 85b827b8b..9518ac5d3 100644 --- a/python/252-Meeting-Rooms.py +++ b/python/252-Meeting-Rooms.py @@ -3,8 +3,9 @@ class Solution: @param intervals: an array of meeting time intervals @return: if a person could attend all meetings """ + def canAttendMeetings(self, intervals): - intervals.sort(key = lambda i : i.start) + intervals.sort(key=lambda i: i.start) for i in range(1, len(intervals)): i1 = intervals[i - 1] @@ -12,4 +13,4 @@ def canAttendMeetings(self, intervals): if i1.end > i2.start: return False - return True + return True diff --git a/python/253-Meeting-Rooms-ii.py b/python/253-Meeting-Rooms-ii.py index f58fb7a20..1495a0361 100644 --- a/python/253-Meeting-Rooms-ii.py +++ b/python/253-Meeting-Rooms-ii.py @@ -3,6 +3,7 @@ class Solution: @param intervals: an array of meeting time intervals @return: the minimum number of conference rooms required """ + def minMeetingRooms(self, intervals): start = sorted([i.start for i in intervals]) end = sorted([i.end for i in intervals]) diff --git a/python/26-Remove-Duplicates-from-Sorted Array.py b/python/26-Remove-Duplicates-from-Sorted Array.py index 33f600927..ff8f96064 100644 --- a/python/26-Remove-Duplicates-from-Sorted Array.py +++ b/python/26-Remove-Duplicates-from-Sorted Array.py @@ -8,9 +8,8 @@ def removeDuplicates(self, nums): i = 0 while i < len(nums): val = nums[i] - while i + 1 < len(nums) and nums[i+1] == val: + while i + 1 < len(nums) and nums[i + 1] == val: nums.remove(val) k += 1 i += 1 return len(nums) - diff --git a/python/261-Graph-Valid-Tree.py b/python/261-Graph-Valid-Tree.py index 0f5e5f36b..cbe6958de 100644 --- a/python/261-Graph-Valid-Tree.py +++ b/python/261-Graph-Valid-Tree.py @@ -1,29 +1,31 @@ -# Problem is free on Lintcode +# Problem is free on Lintcode class Solution: """ @param n: An integer @param edges: a list of undirected edges @return: true if it's a valid tree, or false """ + def validTree(self, n, edges): if not n: - return True - adj = { i:[] for i in range(n) } + return True + adj = {i: [] for i in range(n)} for n1, n2 in edges: adj[n1].append(n2) adj[n2].append(n1) visit = set() + def dfs(i, prev): if i in visit: return False - + visit.add(i) for j in adj[i]: if j == prev: continue if not dfs(j, i): return False - return True - + return True + return dfs(0, -1) and n == len(visit) diff --git a/python/268-Missing-Number.py b/python/268-Missing-Number.py index 1e90165d8..9d39e0456 100644 --- a/python/268-Missing-Number.py +++ b/python/268-Missing-Number.py @@ -1,7 +1,7 @@ class Solution: def missingNumber(self, nums: List[int]) -> int: res = len(nums) - + for i in range(len(nums)): - res += (i - nums[i]) + res += i - nums[i] return res diff --git a/python/269-Alien-Dictionary.py b/python/269-Alien-Dictionary.py index a415f1187..0409db0f7 100644 --- a/python/269-Alien-Dictionary.py +++ b/python/269-Alien-Dictionary.py @@ -2,36 +2,36 @@ class Solution: def alienOrder(self, words: List[str]) -> str: adj = {char: set() for word in words for char in word} - for i in range(len(words)-1): - w1, w2 = words[i], words[i + 1] - minLen = min(len(w1), len(w2)) - if len(w1) > len(w2) and w1[:minLen] == w2[:minLen]: - return '' - for j in range(minLen): - if w1[j] != w2[j]: - print(w1[j], w2[j]) - adj[w1[j]].add(w2[j]) - break - - visited = {} # {char: bool} False visited, True current path + for i in range(len(words) - 1): + w1, w2 = words[i], words[i + 1] + minLen = min(len(w1), len(w2)) + if len(w1) > len(w2) and w1[:minLen] == w2[:minLen]: + return "" + for j in range(minLen): + if w1[j] != w2[j]: + print(w1[j], w2[j]) + adj[w1[j]].add(w2[j]) + break + + visited = {} # {char: bool} False visited, True current path res = [] def dfs(char): - if char in visited: - return visited[char] + if char in visited: + return visited[char] - visited[char] = True + visited[char] = True - for neighChar in adj[char]: - if dfs(neighChar): - return True + for neighChar in adj[char]: + if dfs(neighChar): + return True - visited[char] = False - res.append(char) + visited[char] = False + res.append(char) for char in adj: - if dfs(char): - return '' + if dfs(char): + return "" res.reverse() - return ''.join(res) \ No newline at end of file + return "".join(res) diff --git a/python/27-Remove-Element.py b/python/27-Remove-Element.py index 46f369b47..5e457182c 100644 --- a/python/27-Remove-Element.py +++ b/python/27-Remove-Element.py @@ -5,6 +5,6 @@ def removeElement(self, nums, val): :type val: int :rtype: int """ - for i in range(nums.count(val)): # loop how many val is in the list + for i in range(nums.count(val)): # loop how many val is in the list nums.remove(val) # remove each val one by one - return len(nums) # return len of nums + return len(nums) # return len of nums diff --git a/python/271-Encode-and-Decode-Strings.py b/python/271-Encode-and-Decode-Strings.py index b96c9a028..722f440d7 100644 --- a/python/271-Encode-and-Decode-Strings.py +++ b/python/271-Encode-and-Decode-Strings.py @@ -3,6 +3,7 @@ class Solution: @param: strs: a list of strings @return: encodes a list of strings to a single string. """ + def encode(self, strs): res = "" for s in strs: @@ -13,6 +14,7 @@ def encode(self, strs): @param: str: A string @return: dcodes a single string to a list of strings """ + def decode(self, str): res, i = [], 0 diff --git a/python/28-Implement-strStr.py b/python/28-Implement-strStr.py index e43bb4564..c2095418f 100644 --- a/python/28-Implement-strStr.py +++ b/python/28-Implement-strStr.py @@ -1,8 +1,9 @@ class Solution: def strStr(self, haystack: str, needle: str) -> int: - if needle == "": return 0 + if needle == "": + return 0 lps = [0] * len(needle) - + prevLPS, i = 0, 1 while i < len(needle): if needle[i] == needle[prevLPS]: @@ -14,9 +15,9 @@ def strStr(self, haystack: str, needle: str) -> int: i += 1 else: prevLPS = lps[prevLPS - 1] - - i = 0 # ptr for haystack - j = 0 # ptr for needle + + i = 0 # ptr for haystack + j = 0 # ptr for needle while i < len(haystack): if haystack[i] == needle[j]: i, j = i + 1, j + 1 diff --git a/python/286-Walls-and-Gates.py b/python/286-Walls-and-Gates.py index db5e4fb26..3e01bb8e3 100644 --- a/python/286-Walls-and-Gates.py +++ b/python/286-Walls-and-Gates.py @@ -3,14 +3,20 @@ class Solution: @param rooms: m x n 2D grid @return: nothing """ + def walls_and_gates(self, rooms: List[List[int]]): ROWS, COLS = len(rooms), len(rooms[0]) visit = set() q = deque() def addRooms(r, c): - if (min(r, c) < 0 or r == ROWS or c == COLS or - (r, c) in visit or rooms[r][c] == -1): + if ( + min(r, c) < 0 + or r == ROWS + or c == COLS + or (r, c) in visit + or rooms[r][c] == -1 + ): return visit.add((r, c)) q.append([r, c]) diff --git a/python/287-Find-The-Duplicate-Number.py b/python/287-Find-The-Duplicate-Number.py index cf498bf8b..28460b5d8 100644 --- a/python/287-Find-The-Duplicate-Number.py +++ b/python/287-Find-The-Duplicate-Number.py @@ -6,7 +6,7 @@ def findDuplicate(self, nums: List[int]) -> int: fast = nums[nums[fast]] if slow == fast: break - + slow2 = 0 while True: slow = nums[slow] diff --git a/python/295-Find-Median-from-Data-Stream.py b/python/295-Find-Median-from-Data-Stream.py index d2a5cc404..7a16543b0 100644 --- a/python/295-Find-Median-from-Data-Stream.py +++ b/python/295-Find-Median-from-Data-Stream.py @@ -1,17 +1,16 @@ class MedianFinder: - def __init__(self): """ initialize your data structure here. """ # two heaps, large, small, minheap, maxheap # heaps should be equal size - self.small, self.large = [], [] # maxHeap, minHeap (python default) + self.small, self.large = [], [] # maxHeap, minHeap (python default) def addNum(self, num: int) -> None: heapq.heappush(self.small, -1 * num) - - if (self.small and self.large and (-1 * self.small[0]) > self.large[0]): + + if self.small and self.large and (-1 * self.small[0]) > self.large[0]: val = -1 * heapq.heappop(self.small) heapq.heappush(self.large, val) @@ -21,7 +20,7 @@ def addNum(self, num: int) -> None: if len(self.large) > len(self.small) + 1: val = heapq.heappop(self.large) heapq.heappush(self.small, -1 * val) - + def findMedian(self) -> float: if len(self.small) > len(self.large): return -1 * self.small[0] diff --git a/python/297-Serialize-and-Deserialize-Binary-Tree.py b/python/297-Serialize-and-Deserialize-Binary-Tree.py index 764c08422..5d62ace9c 100644 --- a/python/297-Serialize-and-Deserialize-Binary-Tree.py +++ b/python/297-Serialize-and-Deserialize-Binary-Tree.py @@ -5,8 +5,8 @@ # self.left = None # self.right = None -class Codec: +class Codec: def serialize(self, root): res = [] @@ -17,13 +17,14 @@ def dfs(node): res.append(str(node.val)) dfs(node.left) dfs(node.right) + dfs(root) - return ",".join(res) - + return ",".join(res) + def deserialize(self, data): vals = data.split(",") self.i = 0 - + def dfs(): if vals[self.i] == "N": self.i += 1 @@ -33,4 +34,5 @@ def dfs(): node.left = dfs() node.right = dfs() return node + return dfs() diff --git a/python/3-Longest-Substring-Without-Repeating-Characters.py b/python/3-Longest-Substring-Without-Repeating-Characters.py index e37d07824..4fa9ee4cb 100644 --- a/python/3-Longest-Substring-Without-Repeating-Characters.py +++ b/python/3-Longest-Substring-Without-Repeating-Characters.py @@ -3,7 +3,7 @@ def lengthOfLongestSubstring(self, s: str) -> int: charSet = set() l = 0 res = 0 - + for r in range(len(s)): while s[r] in charSet: charSet.remove(s[l]) diff --git a/python/300-Longest-Increasing-Subsequence.py b/python/300-Longest-Increasing-Subsequence.py index 8799e78b5..854767039 100644 --- a/python/300-Longest-Increasing-Subsequence.py +++ b/python/300-Longest-Increasing-Subsequence.py @@ -1,7 +1,7 @@ class Solution: def lengthOfLIS(self, nums: List[int]) -> int: LIS = [1] * len(nums) - + for i in range(len(nums) - 1, -1, -1): for j in range(i + 1, len(nums)): if nums[i] < nums[j]: diff --git a/python/309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.py b/python/309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.py index 582475cb1..c95b42883 100644 --- a/python/309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.py +++ b/python/309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.py @@ -3,15 +3,15 @@ def maxProfit(self, prices: List[int]) -> int: # State: Buying or Selling? # If Buy -> i + 1 # If Sell -> i + 2 - - dp = {} # key=(i, buying) val=max_profit - + + dp = {} # key=(i, buying) val=max_profit + def dfs(i, buying): if i >= len(prices): return 0 if (i, buying) in dp: return dp[(i, buying)] - + cooldown = dfs(i + 1, buying) if buying: buy = dfs(i + 1, not buying) - prices[i] @@ -20,5 +20,5 @@ def dfs(i, buying): sell = dfs(i + 2, not buying) + prices[i] dp[(i, buying)] = max(sell, cooldown) return dp[(i, buying)] - + return dfs(0, True) diff --git a/python/312-Burst-Balloons.py b/python/312-Burst-Balloons.py index f3199e8ac..0c19c6537 100644 --- a/python/312-Burst-Balloons.py +++ b/python/312-Burst-Balloons.py @@ -2,7 +2,7 @@ class Solution: def maxCoins(self, nums: List[int]) -> int: cache = {} nums = [1] + nums + [1] - + for offset in range(2, len(nums)): for left in range(len(nums) - offset): right = left + offset diff --git a/python/322-Coin-Change.py b/python/322-Coin-Change.py index ef870465a..9cd9b2e0e 100644 --- a/python/322-Coin-Change.py +++ b/python/322-Coin-Change.py @@ -1,8 +1,8 @@ class Solution: def coinChange(self, coins: List[int], amount: int) -> int: - dp = [amount + 1] * (amount + 1) + dp = [amount + 1] * (amount + 1) dp[0] = 0 - + for a in range(1, amount + 1): for c in coins: if a - c >= 0: diff --git a/python/323-Number-of-Connected-Components-in-an-Undirected-Graph.py b/python/323-Number-of-Connected-Components-in-an-Undirected-Graph.py index 4ed6b8345..66d94f6bc 100644 --- a/python/323-Number-of-Connected-Components-in-an-Undirected-Graph.py +++ b/python/323-Number-of-Connected-Components-in-an-Undirected-Graph.py @@ -1,19 +1,20 @@ class UnionFind: def __init__(self): self.f = {} - - def findParent(self,x): - y = self.f.get(x,x) - if x!=y: - y = self.f[x] = self.findParent(y) + + def findParent(self, x): + y = self.f.get(x, x) + if x != y: + y = self.f[x] = self.findParent(y) return y - - def union(self,x,y): + + def union(self, x, y): self.f[self.findParent(x)] = self.findParent(y) + class Solution: def countComponents(self, n: int, edges: List[List[int]]) -> int: dsu = UnionFind() - for a,b in edges: - dsu.union(a,b) - return len(set(dsu.findParent(x) for x in range(n))) \ No newline at end of file + for a, b in edges: + dsu.union(a, b) + return len(set(dsu.findParent(x) for x in range(n))) diff --git a/python/329-Longest-Increasing-Path-in-a-Matrix.py b/python/329-Longest-Increasing-Path-in-a-Matrix.py index bea327654..36eb98d34 100644 --- a/python/329-Longest-Increasing-Path-in-a-Matrix.py +++ b/python/329-Longest-Increasing-Path-in-a-Matrix.py @@ -1,16 +1,14 @@ class Solution: def longestIncreasingPath(self, matrix: List[List[int]]) -> int: ROWS, COLS = len(matrix), len(matrix[0]) - dp = {} # (r, c) -> LIP - + dp = {} # (r, c) -> LIP + def dfs(r, c, prevVal): - if (r < 0 or r == ROWS or - c < 0 or c == COLS or - matrix[r][c] <= prevVal): + if r < 0 or r == ROWS or c < 0 or c == COLS or matrix[r][c] <= prevVal: return 0 if (r, c) in dp: return dp[(r, c)] - + res = 1 res = max(res, 1 + dfs(r + 1, c, matrix[r][c])) res = max(res, 1 + dfs(r - 1, c, matrix[r][c])) diff --git a/python/33-Search-In-Rotated-Sorted-Array.py b/python/33-Search-In-Rotated-Sorted-Array.py index faf1939cd..fe01019d4 100644 --- a/python/33-Search-In-Rotated-Sorted-Array.py +++ b/python/33-Search-In-Rotated-Sorted-Array.py @@ -1,12 +1,12 @@ class Solution: def search(self, nums: List[int], target: int) -> int: l, r = 0, len(nums) - 1 - + while l <= r: mid = (l + r) // 2 if target == nums[mid]: return mid - + # left sorted portion if nums[l] <= nums[mid]: if target > nums[mid] or target < nums[l]: diff --git a/python/332-Reconstruct-Itinerary.py b/python/332-Reconstruct-Itinerary.py index 7ff52ba29..caf32aef1 100644 --- a/python/332-Reconstruct-Itinerary.py +++ b/python/332-Reconstruct-Itinerary.py @@ -1,18 +1,18 @@ class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: - adj = { u:collections.deque() for u, v in tickets } + adj = {u: collections.deque() for u, v in tickets} res = ["JFK"] - + tickets.sort() for u, v in tickets: adj[u].append(v) - + def dfs(cur): if len(res) == len(tickets) + 1: return True if cur not in adj: return False - + temp = list(adj[cur]) for v in temp: adj[cur].popleft() @@ -21,6 +21,7 @@ def dfs(cur): return res res.pop() adj[cur].append(v) - return False + return False + dfs("JFK") return res diff --git a/python/338-Counting-Bits.py b/python/338-Counting-Bits.py index 81e7f3655..42f0a4662 100644 --- a/python/338-Counting-Bits.py +++ b/python/338-Counting-Bits.py @@ -2,7 +2,7 @@ class Solution: def countBits(self, n: int) -> List[int]: dp = [0] * (n + 1) offset = 1 - + for i in range(1, n + 1): if offset * 2 == i: offset = i diff --git a/python/34-Find-First-and-Last-Position-of-Element-in-Sorted-Array.py b/python/34-Find-First-and-Last-Position-of-Element-in-Sorted-Array.py index ca3a84f5f..da6efc986 100644 --- a/python/34-Find-First-and-Last-Position-of-Element-in-Sorted-Array.py +++ b/python/34-Find-First-and-Last-Position-of-Element-in-Sorted-Array.py @@ -3,7 +3,7 @@ def searchRange(self, nums: List[int], target: int) -> List[int]: left = self.binSearch(nums, target, True) right = self.binSearch(nums, target, False) return [left, right] - + # leftBias=[True/False], if false, res is rightBiased def binSearch(self, nums, target, leftBias): l, r = 0, len(nums) - 1 @@ -20,4 +20,4 @@ def binSearch(self, nums, target, leftBias): r = m - 1 else: l = m + 1 - return i + return i diff --git a/python/347-Top-k-frequent-elements.py b/python/347-Top-k-frequent-elements.py index 953241d42..f4238a64e 100644 --- a/python/347-Top-k-frequent-elements.py +++ b/python/347-Top-k-frequent-elements.py @@ -2,17 +2,17 @@ class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: count = {} freq = [[] for i in range(len(nums) + 1)] - + for n in nums: count[n] = 1 + count.get(n, 0) for n, c in count.items(): freq[c].append(n) - + res = [] for i in range(len(freq) - 1, 0, -1): for n in freq[i]: res.append(n) if len(res) == k: return res - + # O(n) diff --git a/python/355-Design-Twitter.py b/python/355-Design-Twitter.py index 7dce41b88..df626a9a5 100644 --- a/python/355-Design-Twitter.py +++ b/python/355-Design-Twitter.py @@ -1,18 +1,17 @@ class Twitter: - def __init__(self): self.count = 0 self.tweetMap = defaultdict(list) # userId -> list of [count, tweetIds] self.followMap = defaultdict(set) # userId -> set of followeeId - + def postTweet(self, userId: int, tweetId: int) -> None: self.tweetMap[userId].append([self.count, tweetId]) self.count -= 1 def getNewsFeed(self, userId: int) -> List[int]: res = [] - minHeap = [] - + minHeap = [] + self.followMap[userId].add(userId) for followeeId in self.followMap[userId]: if followeeId in self.tweetMap: diff --git a/python/36-Valid-Sudoku.py b/python/36-Valid-Sudoku.py index 81821662e..c4ad694d8 100644 --- a/python/36-Valid-Sudoku.py +++ b/python/36-Valid-Sudoku.py @@ -2,18 +2,20 @@ class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: cols = collections.defaultdict(set) rows = collections.defaultdict(set) - squares = collections.defaultdict(set) # key = (r /3, c /3) - + squares = collections.defaultdict(set) # key = (r /3, c /3) + for r in range(9): for c in range(9): if board[r][c] == ".": continue - if (board[r][c] in rows[r] or - board[r][c] in cols[c] or - board[r][c] in squares[(r // 3, c // 3)]): + if ( + board[r][c] in rows[r] + or board[r][c] in cols[c] + or board[r][c] in squares[(r // 3, c // 3)] + ): return False cols[c].add(board[r][c]) rows[r].add(board[r][c]) squares[(r // 3, c // 3)].add(board[r][c]) - + return True diff --git a/python/371-Sum-of-Two-Integers.py b/python/371-Sum-of-Two-Integers.py index 476bfe662..bc8ca5bd3 100644 --- a/python/371-Sum-of-Two-Integers.py +++ b/python/371-Sum-of-Two-Integers.py @@ -1,16 +1,16 @@ class Solution: def getSum(self, a: int, b: int) -> int: - def add(a, b): + def add(a, b): if not a or not b: return a or b - return add(a^b, (a&b) << 1) + return add(a ^ b, (a & b) << 1) - if a*b < 0: # assume a < 0, b > 0 + if a * b < 0: # assume a < 0, b > 0 if a > 0: return self.getSum(b, a) - if add(~a, 1) == b: # -a == b + if add(~a, 1) == b: # -a == b return 0 - if add(~a, 1) < b: # -a < b - return add(~add(add(~a, 1), add(~b, 1)),1) # -add(-a, -b) + if add(~a, 1) < b: # -a < b + return add(~add(add(~a, 1), add(~b, 1)), 1) # -add(-a, -b) - return add(a, b) # a*b >= 0 or (-a) > b > 0 + return add(a, b) # a*b >= 0 or (-a) > b > 0 diff --git a/python/377-Combination-Sum-IV.py b/python/377-Combination-Sum-IV.py index 1b56bb779..cf373708e 100644 --- a/python/377-Combination-Sum-IV.py +++ b/python/377-Combination-Sum-IV.py @@ -1,13 +1,13 @@ class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: - cache = { 0:1 } - + cache = {0: 1} + for total in range(1, target + 1): cache[total] = 0 for n in nums: cache[total] += cache.get(total - n, 0) return cache[target] - + def dfs(total): if total == target: return 1 @@ -15,9 +15,10 @@ def dfs(total): return 0 if total in cache: return cache[total] - + cache[total] = 0 for n in nums: cache[total] += dfs(total + n) return cache[total] + return dfs(0) diff --git a/python/39-Combination-Sum.py b/python/39-Combination-Sum.py index f156c10f8..7df4c4b4f 100644 --- a/python/39-Combination-Sum.py +++ b/python/39-Combination-Sum.py @@ -1,18 +1,18 @@ class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: res = [] - + def dfs(i, cur, total): if total == target: res.append(cur.copy()) return if i >= len(candidates) or total > target: return - + cur.append(candidates[i]) dfs(i, cur, total + candidates[i]) cur.pop() - dfs(i + 1, cur, total) - + dfs(i + 1, cur, total) + dfs(0, [], 0) return res diff --git a/python/394-decode-string.py b/python/394-decode-string.py index 445a81cfd..e4ea9cb3c 100644 --- a/python/394-decode-string.py +++ b/python/394-decode-string.py @@ -1,20 +1,20 @@ class Solution: def decodeString(self, s: str) -> str: stack = [] - + for char in s: if char is not "]": stack.append(char) else: sub_str = "" while stack[-1] is not "[": - sub_str = stack.pop()+sub_str + sub_str = stack.pop() + sub_str stack.pop() multiplier = "" while stack and stack[-1].isdigit(): multiplier = stack.pop() + multiplier - stack.append(int(multiplier)*sub_str) + stack.append(int(multiplier) * sub_str) - return "".join(stack) \ No newline at end of file + return "".join(stack) diff --git a/python/4-median-of-two-sorted-arrays.py b/python/4-median-of-two-sorted-arrays.py index 6ade3557b..88786ebdc 100644 --- a/python/4-median-of-two-sorted-arrays.py +++ b/python/4-median-of-two-sorted-arrays.py @@ -1,24 +1,25 @@ # Time: log(min(n, m)) + class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: A, B = nums1, nums2 total = len(nums1) + len(nums2) half = total // 2 - + if len(B) < len(A): A, B = B, A - + l, r = 0, len(A) - 1 while True: - i = (l + r) // 2 # A - j = half - i - 2 # B - + i = (l + r) // 2 # A + j = half - i - 2 # B + Aleft = A[i] if i >= 0 else float("-infinity") Aright = A[i + 1] if (i + 1) < len(A) else float("infinity") Bleft = B[j] if j >= 0 else float("-infinity") Bright = B[j + 1] if (j + 1) < len(B) else float("infinity") - + # partition is correct if Aleft <= Bright and Bleft <= Aright: # odd diff --git a/python/40-Combination-Sum-II.py b/python/40-Combination-Sum-II.py index e85438173..6c7708fd1 100644 --- a/python/40-Combination-Sum-II.py +++ b/python/40-Combination-Sum-II.py @@ -1,14 +1,15 @@ class Solution: def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: candidates.sort() - + res = [] + def backtrack(cur, pos, target): if target == 0: res.append(cur.copy()) if target <= 0: return - + prev = -1 for i in range(pos, len(candidates)): if candidates[i] == prev: @@ -17,6 +18,6 @@ def backtrack(cur, pos, target): backtrack(cur, i + 1, target - candidates[i]) cur.pop() prev = candidates[i] - + backtrack([], 0, target) return res diff --git a/python/40-Combinations-Sum-ii.py b/python/40-Combinations-Sum-ii.py index 27d39d393..6c7708fd1 100644 --- a/python/40-Combinations-Sum-ii.py +++ b/python/40-Combinations-Sum-ii.py @@ -1,14 +1,15 @@ class Solution: def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: candidates.sort() - + res = [] + def backtrack(cur, pos, target): if target == 0: res.append(cur.copy()) if target <= 0: return - + prev = -1 for i in range(pos, len(candidates)): if candidates[i] == prev: @@ -17,5 +18,6 @@ def backtrack(cur, pos, target): backtrack(cur, i + 1, target - candidates[i]) cur.pop() prev = candidates[i] + backtrack([], 0, target) return res diff --git a/python/410-Split-Array-Largest-Sum.py b/python/410-Split-Array-Largest-Sum.py index bd2f910d1..e7b6c4c44 100644 --- a/python/410-Split-Array-Largest-Sum.py +++ b/python/410-Split-Array-Largest-Sum.py @@ -9,7 +9,7 @@ def canSplit(largest): subarray += 1 curSum = n return subarray + 1 <= m - + l, r = max(nums), sum(nums) res = r while l <= r: diff --git a/python/416-Partition-Equal-Subset-Sum.py b/python/416-Partition-Equal-Subset-Sum.py index 0a3632a91..0fa35c087 100644 --- a/python/416-Partition-Equal-Subset-Sum.py +++ b/python/416-Partition-Equal-Subset-Sum.py @@ -2,11 +2,11 @@ class Solution: def canPartition(self, nums: List[int]) -> bool: if sum(nums) % 2: return False - + dp = set() dp.add(0) target = sum(nums) // 2 - + for i in range(len(nums) - 1, -1, -1): nextDP = set() for t in dp: diff --git a/python/417-Pacific-Atlantic-Waterflow.py b/python/417-Pacific-Atlantic-Waterflow.py index 0bb60579a..ae6aa51fb 100644 --- a/python/417-Pacific-Atlantic-Waterflow.py +++ b/python/417-Pacific-Atlantic-Waterflow.py @@ -2,26 +2,31 @@ class Solution: def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: ROWS, COLS = len(heights), len(heights[0]) pac, atl = set(), set() - + def dfs(r, c, visit, prevHeight): - if ((r, c) in visit or - r < 0 or c < 0 or r == ROWS or c == COLS or - heights[r][c] < prevHeight): + if ( + (r, c) in visit + or r < 0 + or c < 0 + or r == ROWS + or c == COLS + or heights[r][c] < prevHeight + ): return visit.add((r, c)) dfs(r + 1, c, visit, heights[r][c]) dfs(r - 1, c, visit, heights[r][c]) dfs(r, c + 1, visit, heights[r][c]) dfs(r, c - 1, visit, heights[r][c]) - + for c in range(COLS): dfs(0, c, pac, heights[0][c]) dfs(ROWS - 1, c, atl, heights[ROWS - 1][c]) - + for r in range(ROWS): dfs(r, 0, pac, heights[r][0]) dfs(r, COLS - 1, atl, heights[r][COLS - 1]) - + res = [] for r in range(ROWS): for c in range(COLS): diff --git a/python/42-Trapping-Rain-Water.py b/python/42-Trapping-Rain-Water.py index d39a48e5b..954cb6d98 100644 --- a/python/42-Trapping-Rain-Water.py +++ b/python/42-Trapping-Rain-Water.py @@ -1,7 +1,8 @@ class Solution: - def trap(self, height: List[int]) -> int: - if not height: return 0 - + def trap(self, height: List[int]) -> int: + if not height: + return 0 + l, r = 0, len(height) - 1 leftMax, rightMax = height[l], height[r] res = 0 diff --git a/python/424-Longest-Repeating-Character-Replacement.py b/python/424-Longest-Repeating-Character-Replacement.py index 2fdc379d5..7c6864cdc 100644 --- a/python/424-Longest-Repeating-Character-Replacement.py +++ b/python/424-Longest-Repeating-Character-Replacement.py @@ -2,16 +2,16 @@ class Solution: def characterReplacement(self, s: str, k: int) -> int: count = {} res = 0 - + l = 0 maxf = 0 for r in range(len(s)): count[s[r]] = 1 + count.get(s[r], 0) maxf = max(maxf, count[s[r]]) - + if (r - l + 1) - maxf > k: count[s[l]] -= 1 l += 1 - + res = max(res, r - l + 1) return res diff --git a/python/43-Multiply-Strings.py b/python/43-Multiply-Strings.py index 1e4aaa56b..7359d0462 100644 --- a/python/43-Multiply-Strings.py +++ b/python/43-Multiply-Strings.py @@ -2,7 +2,7 @@ class Solution: def multiply(self, num1: str, num2: str) -> str: if "0" in [num1, num2]: return "0" - + res = [0] * (len(num1) + len(num2)) num1, num2 = num1[::-1], num2[::-1] for i1 in range(len(num1)): @@ -11,7 +11,7 @@ def multiply(self, num1: str, num2: str) -> str: res[i1 + i2] += digit res[i1 + i2 + 1] += res[i1 + i2] // 10 res[i1 + i2] = res[i1 + i2] % 10 - + res, beg = res[::-1], 0 while beg < len(res) and res[beg] == 0: beg += 1 diff --git a/python/43-Number_of_Connected_Components_in_an_Undirected_Graph.py b/python/43-Number_of_Connected_Components_in_an_Undirected_Graph.py index 9e2456ff5..560f54e62 100644 --- a/python/43-Number_of_Connected_Components_in_an_Undirected_Graph.py +++ b/python/43-Number_of_Connected_Components_in_an_Undirected_Graph.py @@ -1,4 +1,3 @@ - class Solution: def count_components(self, n: int, edges: List[List[int]]) -> int: parent = [i for i in range(n)] @@ -7,7 +6,7 @@ def count_components(self, n: int, edges: List[List[int]]) -> int: def find_union(node: int) -> None: result = node while result != parent[result]: - parent[result] = parent[parent[result]] # path compression + parent[result] = parent[parent[result]] # path compression result = parent[result] return result @@ -23,9 +22,8 @@ def union(node_1: int, node_2: int): parent[parent_2] = parent_1 rank[parent_1] += rank[parent_2] return 1 - + result = n for node_1, node_2 in edges: result -= union(node_1, node_2) return result - diff --git a/python/435-Non-Overlapping-Intervals.py b/python/435-Non-Overlapping-Intervals.py index f9d1b71e8..510057b4b 100644 --- a/python/435-Non-Overlapping-Intervals.py +++ b/python/435-Non-Overlapping-Intervals.py @@ -1,5 +1,5 @@ class Solution: - def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: + def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: intervals.sort() res = 0 prevEnd = intervals[0][1] diff --git a/python/448-Find-all-Numbers-Disappeared-in-an-Array.py b/python/448-Find-all-Numbers-Disappeared-in-an-Array.py index 45db6bf9e..e0383e10d 100644 --- a/python/448-Find-all-Numbers-Disappeared-in-an-Array.py +++ b/python/448-Find-all-Numbers-Disappeared-in-an-Array.py @@ -3,7 +3,7 @@ def findDisappearedNumbers(self, nums: List[int]) -> List[int]: for n in nums: i = abs(n) - 1 nums[i] = -1 * abs(nums[i]) - + res = [] for i, n in enumerate(nums): if n > 0: diff --git a/python/45-Jump-Game-II.py b/python/45-Jump-Game-II.py index 28a4d095f..7a0fa78a3 100644 --- a/python/45-Jump-Game-II.py +++ b/python/45-Jump-Game-II.py @@ -1,5 +1,5 @@ class Solution: - def jump(self, nums: List[int]) -> int: + def jump(self, nums: List[int]) -> int: l, r = 0, 0 res = 0 while r < (len(nums) - 1): diff --git a/python/46-Permutations.py b/python/46-Permutations.py index 1e263a71a..0e6cfb447 100644 --- a/python/46-Permutations.py +++ b/python/46-Permutations.py @@ -1,15 +1,15 @@ class Solution: def permute(self, nums: List[int]) -> List[List[int]]: res = [] - + # base case if len(nums) == 1: - return [nums[:]] # nums[:] is a deep copy - + return [nums[:]] # nums[:] is a deep copy + for i in range(len(nums)): n = nums.pop(0) perms = self.permute(nums) - + for perm in perms: perm.append(n) res.extend(perms) diff --git a/python/463-Island-Perimeter.py b/python/463-Island-Perimeter.py index b60b55e49..fb45d3031 100644 --- a/python/463-Island-Perimeter.py +++ b/python/463-Island-Perimeter.py @@ -1,21 +1,20 @@ class Solution: def islandPerimeter(self, grid: List[List[int]]) -> int: visit = set() - + def dfs(i, j): - if i >= len(grid) or j >= len(grid[0]) or \ - i < 0 or j < 0 or grid[i][j] == 0: + if i >= len(grid) or j >= len(grid[0]) or i < 0 or j < 0 or grid[i][j] == 0: return 1 if (i, j) in visit: return 0 - + visit.add((i, j)) perim = dfs(i, j + 1) perim += dfs(i + 1, j) perim += dfs(i, j - 1) perim += dfs(i - 1, j) return perim - + for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j]: diff --git a/python/473-Matchsticks-to-Square.py b/python/473-Matchsticks-to-Square.py index fef8256f9..0d94f3029 100644 --- a/python/473-Matchsticks-to-Square.py +++ b/python/473-Matchsticks-to-Square.py @@ -2,14 +2,15 @@ class Solution: def makesquare(self, matchsticks: List[int]) -> bool: length = sum(matchsticks) // 4 sides = [0] * 4 - + if sum(matchsticks) / 4 != length: return False matchsticks.sort(reverse=True) + def backtrack(i): if i == len(matchsticks): return True - + for j in range(4): if sides[j] + matchsticks[i] <= length: sides[j] += matchsticks[i] @@ -17,5 +18,5 @@ def backtrack(i): return True sides[j] -= matchsticks[i] return False - + return backtrack(0) diff --git a/python/48-Rotate-Image.py b/python/48-Rotate-Image.py index 5300ee201..6234ec455 100644 --- a/python/48-Rotate-Image.py +++ b/python/48-Rotate-Image.py @@ -7,19 +7,19 @@ def rotate(self, matrix: List[List[int]]) -> None: while l < r: for i in range(r - l): top, bottom = l, r - + # save the topleft topLeft = matrix[top][l + i] - + # move bottom left into top left matrix[top][l + i] = matrix[bottom - i][l] - + # move bottom right into bottom left matrix[bottom - i][l] = matrix[bottom][r - i] - + # move top right into bottom right matrix[bottom][r - i] = matrix[top + i][r] - + # move top left into top right matrix[top + i][r] = topLeft r -= 1 diff --git a/python/49-Group-Anagrams.py b/python/49-Group-Anagrams.py index fe78b51f1..997f9b2ce 100644 --- a/python/49-Group-Anagrams.py +++ b/python/49-Group-Anagrams.py @@ -3,5 +3,5 @@ def groupAnagrams(self, strs: List[str]) -> List[List[str]]: hashmap = defaultdict(list) for s in strs: # keys can be strings, bcz they are immutable. - hashmap[str(sorted(s))].append(s) + hashmap[str(sorted(s))].append(s) return hashmap.values() diff --git a/python/494-Target-Sum.py b/python/494-Target-Sum.py index 6b05c6574..e8965ecba 100644 --- a/python/494-Target-Sum.py +++ b/python/494-Target-Sum.py @@ -1,14 +1,16 @@ class Solution: def findTargetSumWays(self, nums: List[int], target: int) -> int: - dp = {} # (index, total) -> # of ways - + dp = {} # (index, total) -> # of ways + def backtrack(i, total): if i == len(nums): return 1 if total == target else 0 if (i, total) in dp: return dp[(i, total)] - - dp[(i, total)] = (backtrack(i + 1, total + nums[i]) + - backtrack(i + 1, total - nums[i])) + + dp[(i, total)] = backtrack(i + 1, total + nums[i]) + backtrack( + i + 1, total - nums[i] + ) return dp[(i, total)] + return backtrack(0, 0) diff --git a/python/5-Longest-Palindromic-Substring.py b/python/5-Longest-Palindromic-Substring.py index 587d3d03e..c5eb6e7b7 100644 --- a/python/5-Longest-Palindromic-Substring.py +++ b/python/5-Longest-Palindromic-Substring.py @@ -2,24 +2,24 @@ class Solution: def longestPalindrome(self, s: str) -> str: res = "" resLen = 0 - + for i in range(len(s)): # odd length l, r = i, i while l >= 0 and r < len(s) and s[l] == s[r]: if (r - l + 1) > resLen: - res = s[l:r+1] + res = s[l : r + 1] resLen = r - l + 1 l -= 1 r += 1 - + # even length l, r = i, i + 1 while l >= 0 and r < len(s) and s[l] == s[r]: if (r - l + 1) > resLen: - res = s[l:r+1] + res = s[l : r + 1] resLen = r - l + 1 l -= 1 r += 1 - + return res diff --git a/python/50-Pow(x, n).py b/python/50-Pow(x, n).py index 857443118..c7e77af15 100644 --- a/python/50-Pow(x, n).py +++ b/python/50-Pow(x, n).py @@ -1,11 +1,13 @@ class Solution: def myPow(self, x: float, n: int) -> float: def helper(x, n): - if x == 0: return 0 - if n == 0: return 1 - + if x == 0: + return 0 + if n == 0: + return 1 + res = helper(x * x, n // 2) return x * res if n % 2 else res - + res = helper(x, abs(n)) return res if n >= 0 else 1 / res diff --git a/python/51-N-Queens.py b/python/51-N-Queens.py index 9ebcfa661..49fe67d0c 100644 --- a/python/51-N-Queens.py +++ b/python/51-N-Queens.py @@ -1,31 +1,33 @@ class Solution: def solveNQueens(self, n: int) -> List[List[str]]: col = set() - posDiag = set() # (r + c) - negDiag = set() # (r - c) - + posDiag = set() # (r + c) + negDiag = set() # (r - c) + res = [] board = [["."] * n for i in range(n)] + def backtrack(r): if r == n: copy = ["".join(row) for row in board] res.append(copy) return - + for c in range(n): if c in col or (r + c) in posDiag or (r - c) in negDiag: continue - + col.add(c) posDiag.add(r + c) negDiag.add(r - c) board[r][c] = "Q" - + backtrack(r + 1) - + col.remove(c) posDiag.remove(r + c) negDiag.remove(r - c) board[r][c] = "." + backtrack(0) return res diff --git a/python/518-coin-change-2.py b/python/518-coin-change-2.py index 06d2b5409..163d2d06e 100644 --- a/python/518-coin-change-2.py +++ b/python/518-coin-change-2.py @@ -1,10 +1,10 @@ class Solution: def change(self, amount: int, coins: List[int]) -> int: # MEMOIZATION - # Time: O(n*m) + # Time: O(n*m) # Memory: O(n*m) - cache = {} - + cache = {} + def dfs(i, a): if a == amount: return 1 @@ -14,15 +14,14 @@ def dfs(i, a): return 0 if (i, a) in cache: return cache[(i, a)] - + cache[(i, a)] = dfs(i, a + coins[i]) + dfs(i + 1, a) return cache[(i, a)] - + return dfs(0, 0) - - + # DYNAMIC PROGRAMMING - # Time: O(n*m) + # Time: O(n*m) # Memory: O(n*m) dp = [[0] * (len(coins) + 1) for i in range(amount + 1)] dp[0] = [1] * (len(coins) + 1) @@ -32,20 +31,19 @@ def dfs(i, a): if a - coins[i] >= 0: dp[a][i] += dp[a - coins[i]][i] return dp[amount][0] - - + # DYNAMIC PROGRAMMING - # Time: O(n*m) + # Time: O(n*m) # Memory: O(n) where n = amount dp = [0] * (amount + 1) dp[0] = 1 for i in range(len(coins) - 1, -1, -1): nextDP = [0] * (amount + 1) nextDP[0] = 1 - + for a in range(1, amount + 1): - nextDP[a] = dp[a] + nextDP[a] = dp[a] if a - coins[i] >= 0: - nextDP[a] += nextDP[a - coins[i]] + nextDP[a] += nextDP[a - coins[i]] dp = nextDP return dp[amount] diff --git a/python/53-Maximum-Subarray.py b/python/53-Maximum-Subarray.py index 32f6defeb..b2fc36d57 100644 --- a/python/53-Maximum-Subarray.py +++ b/python/53-Maximum-Subarray.py @@ -1,7 +1,7 @@ class Solution: def maxSubArray(self, nums: List[int]) -> int: res = nums[0] - + total = 0 for n in nums: total += n diff --git a/python/54-Spiral-Matrix.py b/python/54-Spiral-Matrix.py index f0226be82..b6a96b40d 100644 --- a/python/54-Spiral-Matrix.py +++ b/python/54-Spiral-Matrix.py @@ -3,7 +3,7 @@ def spiralOrder(self, matrix: List[List[int]]) -> List[int]: res = [] left, right = 0, len(matrix[0]) top, bottom = 0, len(matrix) - + while left < right and top < bottom: # get every i in the top row for i in range(left, right): @@ -23,5 +23,5 @@ def spiralOrder(self, matrix: List[List[int]]) -> List[int]: for i in range(bottom - 1, top - 1, -1): res.append(matrix[i][left]) left += 1 - + return res diff --git a/python/543-Diameter-of-Binary-Tree.py b/python/543-Diameter-of-Binary-Tree.py index 8598087b3..46a465649 100644 --- a/python/543-Diameter-of-Binary-Tree.py +++ b/python/543-Diameter-of-Binary-Tree.py @@ -7,15 +7,15 @@ class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: res = [0] - + def dfs(root): if not root: return -1 left = dfs(root.left) right = dfs(root.right) res[0] = max(res[0], 2 + left + right) - + return 1 + max(left, right) - + dfs(root) return res[0] diff --git a/python/55-Jump-Game.py b/python/55-Jump-Game.py index 5c6a88dcb..4163d7c0e 100644 --- a/python/55-Jump-Game.py +++ b/python/55-Jump-Game.py @@ -1,7 +1,7 @@ class Solution: def canJump(self, nums: List[int]) -> bool: - goal = len(nums) -1 - + goal = len(nums) - 1 + for i in range(len(nums) - 2, -1, -1): if i + nums[i] >= goal: goal = i diff --git a/python/56-Merge-Intervals.py b/python/56-Merge-Intervals.py index 5b95bfe8b..90bfd1163 100644 --- a/python/56-Merge-Intervals.py +++ b/python/56-Merge-Intervals.py @@ -1,12 +1,12 @@ class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: - intervals.sort(key = lambda pair : pair[0]) + intervals.sort(key=lambda pair: pair[0]) output = [intervals[0]] - + for start, end in intervals: lastEnd = output[-1][1] - - if start <= lastEnd: + + if start <= lastEnd: # merge output[-1][1] = max(lastEnd, end) else: diff --git a/python/567-Permutation-in-String.py b/python/567-Permutation-in-String.py index 45093bb68..10fea3f0c 100644 --- a/python/567-Permutation-in-String.py +++ b/python/567-Permutation-in-String.py @@ -1,28 +1,30 @@ class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: - if len(s1) > len(s2): return False - + if len(s1) > len(s2): + return False + s1Count, s2Count = [0] * 26, [0] * 26 for i in range(len(s1)): - s1Count[ord(s1[i]) - ord('a')] += 1 - s2Count[ord(s2[i]) - ord('a')] += 1 - + s1Count[ord(s1[i]) - ord("a")] += 1 + s2Count[ord(s2[i]) - ord("a")] += 1 + matches = 0 for i in range(26): - matches += (1 if s1Count[i] == s2Count[i] else 0) - + matches += 1 if s1Count[i] == s2Count[i] else 0 + l = 0 for r in range(len(s1), len(s2)): - if matches == 26: return True - - index = ord(s2[r]) - ord('a') + if matches == 26: + return True + + index = ord(s2[r]) - ord("a") s2Count[index] += 1 if s1Count[index] == s2Count[index]: matches += 1 elif s1Count[index] + 1 == s2Count[index]: matches -= 1 - - index = ord(s2[l]) - ord('a') + + index = ord(s2[l]) - ord("a") s2Count[index] -= 1 if s1Count[index] == s2Count[index]: matches += 1 diff --git a/python/57-Insert-Interval.py b/python/57-Insert-Interval.py index e454bc19f..c92a4aa7c 100644 --- a/python/57-Insert-Interval.py +++ b/python/57-Insert-Interval.py @@ -1,7 +1,9 @@ class Solution: - def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: + def insert( + self, intervals: List[List[int]], newInterval: List[int] + ) -> List[List[int]]: res = [] - + for i in range(len(intervals)): if newInterval[1] < intervals[i][0]: res.append(newInterval) @@ -9,6 +11,9 @@ def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[Lis elif newInterval[0] > intervals[i][1]: res.append(intervals[i]) else: - newInterval = [min(newInterval[0], intervals[i][0]), max(newInterval[1], intervals[i][1])] + newInterval = [ + min(newInterval[0], intervals[i][0]), + max(newInterval[1], intervals[i][1]), + ] res.append(newInterval) return res diff --git a/python/572-Subtree-of-Another-Tree.py b/python/572-Subtree-of-Another-Tree.py index 2fcdadca8..0bbfa09a6 100644 --- a/python/572-Subtree-of-Another-Tree.py +++ b/python/572-Subtree-of-Another-Tree.py @@ -6,18 +6,18 @@ # self.right = right class Solution: def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: - if not t: return True - if not s: return False - + if not t: + return True + if not s: + return False + if self.sameTree(s, t): return True - return (self.isSubtree(s.left, t) or - self.isSubtree(s.right, t)) - + return self.isSubtree(s.left, t) or self.isSubtree(s.right, t) + def sameTree(self, s, t): if not s and not t: return True if s and t and s.val == t.val: - return (self.sameTree(s.left, t.left) and - self.sameTree(s.right, t.right)) + return self.sameTree(s.left, t.left) and self.sameTree(s.right, t.right) return False diff --git a/python/617-Merge-Two-Binary-Trees.py b/python/617-Merge-Two-Binary-Trees.py index 1c42af8c8..51112226e 100644 --- a/python/617-Merge-Two-Binary-Trees.py +++ b/python/617-Merge-Two-Binary-Trees.py @@ -8,11 +8,11 @@ class Solution: def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if not t1 and not t2: return None - + v1 = t1.val if t1 else 0 v2 = t2.val if t2 else 0 root = TreeNode(v1 + v2) - + root.left = self.mergeTrees(t1.left if t1 else None, t2.left if t2 else None) root.right = self.mergeTrees(t1.right if t1 else None, t2.right if t2 else None) return root diff --git a/python/62-Unique-Paths.py b/python/62-Unique-Paths.py index 399b27748..c5c418de6 100644 --- a/python/62-Unique-Paths.py +++ b/python/62-Unique-Paths.py @@ -1,12 +1,12 @@ class Solution: def uniquePaths(self, m: int, n: int) -> int: row = [1] * n - + for i in range(m - 1): newRow = [1] * n for j in range(n - 2, -1, -1): newRow[j] = newRow[j + 1] + row[j] row = newRow return row[0] - + # O(n * m) O(n) diff --git a/python/621-Task-Scheduler.py b/python/621-Task-Scheduler.py index 2dd9a41a8..256094744 100644 --- a/python/621-Task-Scheduler.py +++ b/python/621-Task-Scheduler.py @@ -1,14 +1,14 @@ class Solution: - def leastInterval(self, tasks: List[str], n: int) -> int: + def leastInterval(self, tasks: List[str], n: int) -> int: count = Counter(tasks) maxHeap = [-cnt for cnt in count.values()] heapq.heapify(maxHeap) - + time = 0 - q = deque() # pairs of [-cnt, idleTime] + q = deque() # pairs of [-cnt, idleTime] while maxHeap or q: time += 1 - + if not maxHeap: time = q[0][1] else: @@ -16,5 +16,5 @@ def leastInterval(self, tasks: List[str], n: int) -> int: if cnt: q.append([cnt, time + n]) if q and q[0][1] == time: - heapq.heappush(maxHeap, q.popleft()[0]) + heapq.heappush(maxHeap, q.popleft()[0]) return time diff --git a/python/647-Palindromic-Substrings.py b/python/647-Palindromic-Substrings.py index b622cbfef..ea15f293d 100644 --- a/python/647-Palindromic-Substrings.py +++ b/python/647-Palindromic-Substrings.py @@ -1,12 +1,12 @@ class Solution: def countSubstrings(self, s: str) -> int: res = 0 - + for i in range(len(s)): res += self.countPali(s, i, i) res += self.countPali(s, i, i + 1) return res - + def countPali(self, s, l, r): res = 0 while l >= 0 and r < len(s) and s[l] == s[r]: diff --git a/python/658-Find-K-Closest-Elements.py b/python/658-Find-K-Closest-Elements.py index a80f8c5d4..8a6c35c67 100644 --- a/python/658-Find-K-Closest-Elements.py +++ b/python/658-Find-K-Closest-Elements.py @@ -3,40 +3,43 @@ class Solution: def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: l, r = 0, len(arr) - 1 - + # Find index of x or the closest val to x val, idx = arr[0], 0 while l <= r: m = (l + r) // 2 curDiff, resDiff = abs(arr[m] - x), abs(val - x) - if (curDiff < resDiff or - (curDiff == resDiff and arr[m] < val)): + if curDiff < resDiff or (curDiff == resDiff and arr[m] < val): val, idx = arr[m], m - if arr[m] < x: l = m + 1 - elif arr[m] > x: r = m - 1 - else: break - - l = r = idx + if arr[m] < x: + l = m + 1 + elif arr[m] > x: + r = m - 1 + else: + break + + l = r = idx for i in range(k - 1): - if l == 0: + if l == 0: r += 1 - elif r == len(arr) - 1 or x - arr[l-1] <= arr[r+1] - x: + elif r == len(arr) - 1 or x - arr[l - 1] <= arr[r + 1] - x: l -= 1 else: - r += 1 - return arr[l:r+1] - + r += 1 + return arr[l : r + 1] + + # Log(n-k) + k # Elegant but very difficult to understand class Solution: def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: l, r = 0, len(arr) - k - + while l < r: m = (l + r) // 2 if x - arr[m] > arr[m + k] - x: l = m + 1 - else: + else: r = m - return arr[l:l+k] + return arr[l : l + k] diff --git a/python/66-Plus-One.py b/python/66-Plus-One.py index a13ba3d6a..6287d6c9c 100644 --- a/python/66-Plus-One.py +++ b/python/66-Plus-One.py @@ -3,7 +3,7 @@ def plusOne(self, digits: List[int]) -> List[int]: one = 1 i = 0 digits = digits[::-1] - + while one: if i < len(digits): if digits[i] == 9: diff --git a/python/673-Number-of-Longest-Increasing-Subsequence.py b/python/673-Number-of-Longest-Increasing-Subsequence.py index 7e84ab9d4..a34bc1dfd 100644 --- a/python/673-Number-of-Longest-Increasing-Subsequence.py +++ b/python/673-Number-of-Longest-Increasing-Subsequence.py @@ -1,21 +1,22 @@ class Solution: def findNumberOfLIS(self, nums: List[int]) -> int: # 1. O(n^2) Recursive solution with Caching - - dp = {} # key = index, value = [length of LIS, count] - lenLIS, res = 0, 0 # length of LIS, count of LIS - + + dp = {} # key = index, value = [length of LIS, count] + lenLIS, res = 0, 0 # length of LIS, count of LIS + def dfs(i): - if i in dp: return dp[i] - - maxLen, maxCnt = 1, 1 # length and count of LIS + if i in dp: + return dp[i] + + maxLen, maxCnt = 1, 1 # length and count of LIS for j in range(i + 1, len(nums)): - if nums[j] > nums[i]: # make sure increasing order + if nums[j] > nums[i]: # make sure increasing order length, count = dfs(j) if length + 1 > maxLen: maxLen, maxCnt = length + 1, count elif length + 1 == maxLen: - maxCnt += count + maxCnt += count nonlocal lenLIS, res if maxLen > lenLIS: lenLIS, res = maxLen, maxCnt @@ -24,21 +25,22 @@ def dfs(i): dp[i] = [maxLen, maxCnt] return dp[i] - for i in range(len(nums)): dfs(i) + for i in range(len(nums)): + dfs(i) return res - - # 2. O(n^2) Dynamic Programming - - dp = {} # key = index, value = [length of LIS, count] - lenLIS, res = 0, 0 # length of LIS, count of LIS - + + # 2. O(n^2) Dynamic Programming + + dp = {} # key = index, value = [length of LIS, count] + lenLIS, res = 0, 0 # length of LIS, count of LIS + # i = start of subseq for i in range(len(nums) - 1, -1, -1): - maxLen, maxCnt = 1, 1 # len, cnt of LIS start from i - + maxLen, maxCnt = 1, 1 # len, cnt of LIS start from i + for j in range(i + 1, len(nums)): if nums[j] > nums[i]: - length, count = dp[j] # len, cnt of LIS start from j + length, count = dp[j] # len, cnt of LIS start from j if length + 1 > maxLen: maxLen, maxCnt = length + 1, count elif length + 1 == maxLen: @@ -48,5 +50,5 @@ def dfs(i): elif maxLen == lenLIS: res += maxCnt dp[i] = [maxLen, maxCnt] - + return res diff --git a/python/678-Valid-Parenthesis-String.py b/python/678-Valid-Parenthesis-String.py index 16d154fa5..3b36c49eb 100644 --- a/python/678-Valid-Parenthesis-String.py +++ b/python/678-Valid-Parenthesis-String.py @@ -1,30 +1,32 @@ # Dynamic Programming: O(n^2) class Solution: def checkValidString(self, s: str) -> bool: - dp = { (len(s), 0) : True } # key=(i, leftCount) -> isValid + dp = {(len(s), 0): True} # key=(i, leftCount) -> isValid + def dfs(i, left): if i == len(s) or left < 0: return left == 0 if (i, left) in dp: return dp[(i, left)] - + if s[i] == "(": dp[(i, left)] = dfs(i + 1, left + 1) elif s[i] == ")": - dp[(i, left)] = dfs(i + 1, left - 1) + dp[(i, left)] = dfs(i + 1, left - 1) else: - dp[(i, left)] = (dfs(i + 1, left + 1) or - dfs(i + 1, left - 1) or - dfs(i + 1, left)) + dp[(i, left)] = ( + dfs(i + 1, left + 1) or dfs(i + 1, left - 1) or dfs(i + 1, left) + ) return dp[(i, left)] - + return dfs(0, 0) - + + # Greedy: O(n) class Solution: def checkValidString(self, s: str) -> bool: leftMin, leftMax = 0, 0 - + for c in s: if c == "(": leftMin, leftMax = leftMin + 1, leftMax + 1 @@ -34,6 +36,6 @@ def checkValidString(self, s: str) -> bool: leftMin, leftMax = leftMin - 1, leftMax + 1 if leftMax < 0: return False - if leftMin < 0: # required because -> s = ( * ) ( + if leftMin < 0: # required because -> s = ( * ) ( leftMin = 0 return leftMin == 0 diff --git a/python/684-Redundant-Connection.py b/python/684-Redundant-Connection.py index 0b1c7ed17..4c09bf43a 100644 --- a/python/684-Redundant-Connection.py +++ b/python/684-Redundant-Connection.py @@ -2,19 +2,20 @@ class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: par = [i for i in range(len(edges) + 1)] rank = [1] * (len(edges) + 1) - + def find(n): p = par[n] while p != par[p]: par[p] = par[par[p]] p = par[p] return p - + # return False if already unioned def union(n1, n2): p1, p2 = find(n1), find(n2) - - if p1 == p2: return False + + if p1 == p2: + return False if rank[p1] > rank[p2]: par[p2] = p1 rank[p1] += rank[p2] @@ -22,7 +23,7 @@ def union(n1, n2): par[p1] = p2 rank[p2] += rank[p1] return True - + for n1, n2 in edges: if not union(n1, n2): return [n1, n2] diff --git a/python/695-Max-Area-of-Island.py b/python/695-Max-Area-of-Island.py index 8ca570a6a..3b913a6e2 100644 --- a/python/695-Max-Area-of-Island.py +++ b/python/695-Max-Area-of-Island.py @@ -2,16 +2,20 @@ class Solution: def maxAreaOfIsland(self, grid: List[List[int]]) -> int: ROWS, COLS = len(grid), len(grid[0]) visit = set() - + def dfs(r, c): - if (r < 0 or r == ROWS or c < 0 or c == COLS or - grid[r][c] == 0 or (r, c) in visit): + if ( + r < 0 + or r == ROWS + or c < 0 + or c == COLS + or grid[r][c] == 0 + or (r, c) in visit + ): return 0 visit.add((r, c)) - return (1 + dfs(r + 1, c) + - dfs(r - 1, c) + - dfs(r, c + 1) + - dfs(r, c - 1)) + return 1 + dfs(r + 1, c) + dfs(r - 1, c) + dfs(r, c + 1) + dfs(r, c - 1) + area = 0 for r in range(ROWS): for c in range(COLS): diff --git a/python/7-Reverse-Integer.py b/python/7-Reverse-Integer.py index 9d858a78f..01e9c138a 100644 --- a/python/7-Reverse-Integer.py +++ b/python/7-Reverse-Integer.py @@ -3,19 +3,17 @@ def reverse(self, x: int) -> int: # Integer.MAX_VALUE = 2147483647 (end with 7) # Integer.MIN_VALUE = -2147483648 (end with -8 ) - MIN = -2147483648 # -2^31, + MIN = -2147483648 # -2^31, MAX = 2147483647 # 2^31 - 1 res = 0 while x: - digit = int(math.fmod(x, 10)) # (python dumb) -1 % 10 = 9 - x = int(x / 10) # (python dumb) -1 // 10 = -1 - - if (res > MAX // 10 or - (res == MAX // 10 and digit >= MAX % 10)): + digit = int(math.fmod(x, 10)) # (python dumb) -1 % 10 = 9 + x = int(x / 10) # (python dumb) -1 // 10 = -1 + + if res > MAX // 10 or (res == MAX // 10 and digit >= MAX % 10): return 0 - if (res < MIN // 10 or - (res == MIN // 10 and digit <= MIN % 10)): + if res < MIN // 10 or (res == MIN // 10 and digit <= MIN % 10): return 0 res = (res * 10) + digit diff --git a/python/70-Climbing-Stairs.py b/python/70-Climbing-Stairs.py index 2bb252058..e41decaba 100644 --- a/python/70-Climbing-Stairs.py +++ b/python/70-Climbing-Stairs.py @@ -1,8 +1,9 @@ class Solution: def climbStairs(self, n: int) -> int: - if n <= 3: return n + if n <= 3: + return n n1, n2 = 2, 3 - + for i in range(4, n + 1): temp = n1 + n2 n1 = n2 diff --git a/python/703-Kth-Largest-Element-in-a-Stream.py b/python/703-Kth-Largest-Element-in-a-Stream.py index fc4ee26b4..f159a0693 100644 --- a/python/703-Kth-Largest-Element-in-a-Stream.py +++ b/python/703-Kth-Largest-Element-in-a-Stream.py @@ -1,5 +1,4 @@ class KthLargest: - def __init__(self, k: int, nums: List[int]): # minHeap w/ K largest integers self.minHeap, self.k = nums, k diff --git a/python/704-Binary-Search.py b/python/704-Binary-Search.py index 88eb0325c..df95ce190 100644 --- a/python/704-Binary-Search.py +++ b/python/704-Binary-Search.py @@ -1,9 +1,9 @@ class Solution: def search(self, nums: List[int], target: int) -> int: l, r = 0, len(nums) - 1 - + while l <= r: - m = l + ((r - l) // 2) # (l + r) // 2 can lead to overflow + m = l + ((r - l) // 2) # (l + r) // 2 can lead to overflow if nums[m] > target: r = m - 1 elif nums[m] < target: diff --git a/python/72-Edit-Distance.py b/python/72-Edit-Distance.py index dc84dc7a9..68c05d699 100644 --- a/python/72-Edit-Distance.py +++ b/python/72-Edit-Distance.py @@ -1,12 +1,12 @@ class Solution: def minDistance(self, word1: str, word2: str) -> int: dp = [[float("inf")] * (len(word2) + 1) for i in range(len(word1) + 1)] - + for j in range(len(word2) + 1): dp[len(word1)][j] = len(word2) - j for i in range(len(word1) + 1): dp[i][len(word2)] = len(word1) - i - + for i in range(len(word1) - 1, -1, -1): for j in range(len(word2) - 1, -1, -1): if word1[i] == word2[j]: diff --git a/python/724-Find-Pivot-Index.py b/python/724-Find-Pivot-Index.py index 1a094985f..5feddd63f 100644 --- a/python/724-Find-Pivot-Index.py +++ b/python/724-Find-Pivot-Index.py @@ -1,7 +1,7 @@ class Solution: def pivotIndex(self, nums: List[int]) -> int: - total = sum(nums) # O(n) - + total = sum(nums) # O(n) + leftSum = 0 for i in range(len(nums)): rightSum = total - nums[i] - leftSum diff --git a/python/73-Set-Matrix-Zeroes.py b/python/73-Set-Matrix-Zeroes.py index 4c960ec64..d994fb706 100644 --- a/python/73-Set-Matrix-Zeroes.py +++ b/python/73-Set-Matrix-Zeroes.py @@ -3,7 +3,7 @@ def setZeroes(self, matrix: List[List[int]]) -> None: # O(1) ROWS, COLS = len(matrix), len(matrix[0]) rowZero = False - + # determine which rows/cols need to be zero for r in range(ROWS): for c in range(COLS): @@ -13,16 +13,16 @@ def setZeroes(self, matrix: List[List[int]]) -> None: matrix[r][0] = 0 else: rowZero = True - + for r in range(1, ROWS): for c in range(1, COLS): if matrix[0][c] == 0 or matrix[r][0] == 0: matrix[r][c] = 0 - + if matrix[0][0] == 0: for r in range(ROWS): matrix[r][0] = 0 - + if rowZero: for c in range(COLS): matrix[0][c] = 0 diff --git a/python/739-Daily-Temperatures.py b/python/739-Daily-Temperatures.py index a7deea595..d6dc52aa8 100644 --- a/python/739-Daily-Temperatures.py +++ b/python/739-Daily-Temperatures.py @@ -1,11 +1,11 @@ class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: res = [0] * len(temperatures) - stack = [] # pair: [temp, index] - + stack = [] # pair: [temp, index] + for i, t in enumerate(temperatures): while stack and t > stack[-1][0]: stackT, stackInd = stack.pop() - res[stackInd] = (i - stackInd) + res[stackInd] = i - stackInd stack.append((t, i)) return res diff --git a/python/74-Search-a-2D-Matrix.py b/python/74-Search-a-2D-Matrix.py index b4f31ad05..ec5686310 100644 --- a/python/74-Search-a-2D-Matrix.py +++ b/python/74-Search-a-2D-Matrix.py @@ -1,7 +1,7 @@ class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: ROWS, COLS = len(matrix), len(matrix[0]) - + top, bot = 0, ROWS - 1 while top <= bot: row = (top + bot) // 2 @@ -11,7 +11,7 @@ def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: bot = row - 1 else: break - + if not (top <= bot): return False diff --git a/python/743-Network-Delay-Time.py b/python/743-Network-Delay-Time.py index beb6613ec..91d46186f 100644 --- a/python/743-Network-Delay-Time.py +++ b/python/743-Network-Delay-Time.py @@ -3,7 +3,7 @@ def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: edges = collections.defaultdict(list) for u, v, w in times: edges[u].append((v, w)) - + minHeap = [(0, k)] visit = set() t = 0 @@ -13,10 +13,10 @@ def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: continue visit.add(n1) t = max(t, w1) - + for n2, w2 in edges[n1]: if n2 not in visit: heapq.heappush(minHeap, (w1 + w2, n2)) return t if len(visit) == n else -1 - + # O(E * logV) diff --git a/python/746-Min-Cost-Climbing-Stairs.py b/python/746-Min-Cost-Climbing-Stairs.py index e7ceadc8e..475510594 100644 --- a/python/746-Min-Cost-Climbing-Stairs.py +++ b/python/746-Min-Cost-Climbing-Stairs.py @@ -1,8 +1,8 @@ class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: cost.append(0) - + for i in range(len(cost) - 3, -1, -1): cost[i] += min(cost[i + 1], cost[i + 2]) - + return min(cost[0], cost[1]) diff --git a/python/752-Open-the-Lock.py b/python/752-Open-the-Lock.py index 179ea8504..121d9e1b6 100644 --- a/python/752-Open-the-Lock.py +++ b/python/752-Open-the-Lock.py @@ -2,19 +2,19 @@ class Solution: def openLock(self, deadends: List[str], target: str) -> int: if "0000" in deadends: return -1 - + def children(wheel): res = [] for i in range(4): digit = str((int(wheel[i]) + 1) % 10) - res.append(wheel[:i] + digit + wheel[i+1:]) + res.append(wheel[:i] + digit + wheel[i + 1 :]) digit = str((int(wheel[i]) + 10 - 1) % 10) - res.append(wheel[:i] + digit + wheel[i+1:]) - return res - + res.append(wheel[:i] + digit + wheel[i + 1 :]) + return res + q = deque() visit = set(deadends) - q.append(["0000", 0]) # [wheel, turns] + q.append(["0000", 0]) # [wheel, turns] while q: wheel, turns = q.popleft() if wheel == target: @@ -23,4 +23,4 @@ def children(wheel): if child not in visit: visit.add(child) q.append([child, turns + 1]) - return -1 + return -1 diff --git a/python/76-Minimum-Window-Substring.py b/python/76-Minimum-Window-Substring.py index 9f601bb57..f16af338a 100644 --- a/python/76-Minimum-Window-Substring.py +++ b/python/76-Minimum-Window-Substring.py @@ -1,30 +1,31 @@ class Solution: def minWindow(self, s: str, t: str) -> str: - if t == "": return "" - + if t == "": + return "" + countT, window = {}, {} for c in t: countT[c] = 1 + countT.get(c, 0) - + have, need = 0, len(countT) res, resLen = [-1, -1], float("infinity") l = 0 for r in range(len(s)): c = s[r] window[c] = 1 + window.get(c, 0) - + if c in countT and window[c] == countT[c]: have += 1 - + while have == need: # update our result if (r - l + 1) < resLen: res = [l, r] - resLen = (r - l + 1) + resLen = r - l + 1 # pop from the left of our window window[s[l]] -= 1 if s[l] in countT and window[s[l]] < countT[s[l]]: have -= 1 l += 1 l, r = res - return s[l:r+1] if resLen != float("infinity") else "" + return s[l : r + 1] if resLen != float("infinity") else "" diff --git a/python/763-Partition-Labels.py b/python/763-Partition-Labels.py index 0594c1d39..da414eb4b 100644 --- a/python/763-Partition-Labels.py +++ b/python/763-Partition-Labels.py @@ -6,7 +6,7 @@ def partitionLabels(self, S: str) -> List[int]: for j in range(length): c = S[j] count[c] = j - + curLen = 0 goal = 0 while i < length: @@ -17,5 +17,5 @@ def partitionLabels(self, S: str) -> List[int]: if goal == i: res.append(curLen) curLen = 0 - i += 1 + i += 1 return res diff --git a/python/767-Reorganize-String.py b/python/767-Reorganize-String.py index 85cd89593..e78099ed6 100644 --- a/python/767-Reorganize-String.py +++ b/python/767-Reorganize-String.py @@ -1,9 +1,9 @@ class Solution: def reorganizeString(self, s: str) -> str: - count = Counter(s) # Hashmap, count each char + count = Counter(s) # Hashmap, count each char maxHeap = [[-cnt, char] for char, cnt in count.items()] - heapq.heapify(maxHeap) # O(n) - + heapq.heapify(maxHeap) # O(n) + prev = None res = "" while maxHeap or prev: @@ -13,7 +13,7 @@ def reorganizeString(self, s: str) -> str: cnt, char = heapq.heappop(maxHeap) res += char cnt += 1 - + if prev: heapq.heappush(maxHeap, prev) prev = None diff --git a/python/778-Swim-in-Rising-Water.py b/python/778-Swim-in-Rising-Water.py index d00030567..d6a284ddf 100644 --- a/python/778-Swim-in-Rising-Water.py +++ b/python/778-Swim-in-Rising-Water.py @@ -2,9 +2,9 @@ class Solution: def swimInWater(self, grid: List[List[int]]) -> int: N = len(grid) visit = set() - minH = [[grid[0][0], 0, 0]] # (time/max-height, r, c) - directions = [[0, 1], [0, -1], [1, 0], [-1 ,0]] - + minH = [[grid[0][0], 0, 0]] # (time/max-height, r, c) + directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] + visit.add((0, 0)) while minH: t, r, c = heapq.heappop(minH) @@ -12,9 +12,13 @@ def swimInWater(self, grid: List[List[int]]) -> int: return t for dr, dc in directions: neiR, neiC = r + dr, c + dc - if (neiR < 0 or neiC < 0 or - neiR == N or neiC == N or - (neiR, neiC) in visit): + if ( + neiR < 0 + or neiC < 0 + or neiR == N + or neiC == N + or (neiR, neiC) in visit + ): continue visit.add((neiR, neiC)) heapq.heappush(minH, [max(t, grid[neiR][neiC]), neiR, neiC]) diff --git a/python/78-Subsets.py b/python/78-Subsets.py index 206dc54b2..f328dfd85 100644 --- a/python/78-Subsets.py +++ b/python/78-Subsets.py @@ -1,8 +1,9 @@ class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: res = [] - + subset = [] + def dfs(i): if i >= len(nums): res.append(subset.copy()) @@ -13,6 +14,6 @@ def dfs(i): # decision NOT to include nums[i] subset.pop() dfs(i + 1) - + dfs(0) return res diff --git a/python/787-Cheapest-Flights-within-K-stops.py b/python/787-Cheapest-Flights-within-K-stops.py index 767e1b98e..aa1a68fdf 100644 --- a/python/787-Cheapest-Flights-within-K-stops.py +++ b/python/787-Cheapest-Flights-within-K-stops.py @@ -1,12 +1,14 @@ class Solution: - def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: + def findCheapestPrice( + self, n: int, flights: List[List[int]], src: int, dst: int, k: int + ) -> int: prices = [float("inf")] * n prices[src] = 0 - + for i in range(k + 1): tmpPrices = prices.copy() - - for s, d, p in flights: # s=source, d=dest, p=price + + for s, d, p in flights: # s=source, d=dest, p=price if prices[s] == float("inf"): continue if prices[s] + p < tmpPrices[d]: diff --git a/python/79-Word-Search.py b/python/79-Word-Search.py index 5c6b99a42..e33f8cf6c 100644 --- a/python/79-Word-Search.py +++ b/python/79-Word-Search.py @@ -2,24 +2,32 @@ class Solution: def exist(self, board: List[List[str]], word: str) -> bool: ROWS, COLS = len(board), len(board[0]) path = set() - + def dfs(r, c, i): if i == len(word): return True - if (min(r, c) < 0 or r >= ROWS or c >= COLS or - word[i] != board[r][c] or (r, c) in path): + if ( + min(r, c) < 0 + or r >= ROWS + or c >= COLS + or word[i] != board[r][c] + or (r, c) in path + ): return False path.add((r, c)) - res = (dfs(r + 1, c, i + 1) or - dfs(r - 1, c, i + 1) or - dfs(r, c + 1, i + 1) or - dfs(r, c - 1, i + 1)) + res = ( + dfs(r + 1, c, i + 1) + or dfs(r - 1, c, i + 1) + or dfs(r, c + 1, i + 1) + or dfs(r, c - 1, i + 1) + ) path.remove((r, c)) return res - + for r in range(ROWS): for c in range(COLS): - if dfs(r, c, 0): return True + if dfs(r, c, 0): + return True return False - + # O(n * m * 4^n) diff --git a/python/84-Largest-Rectangle-in-Histogram.py b/python/84-Largest-Rectangle-in-Histogram.py index 8f84af583..26607c75a 100644 --- a/python/84-Largest-Rectangle-in-Histogram.py +++ b/python/84-Largest-Rectangle-in-Histogram.py @@ -1,8 +1,8 @@ class Solution: def largestRectangleArea(self, heights: List[int]) -> int: maxArea = 0 - stack = [] # pair: (index, height) - + stack = [] # pair: (index, height) + for i, h in enumerate(heights): start = i while stack and stack[-1][1] > h: @@ -10,7 +10,7 @@ def largestRectangleArea(self, heights: List[int]) -> int: maxArea = max(maxArea, height * (i - index)) start = index stack.append((start, h)) - + for i, h in stack: maxArea = max(maxArea, h * (len(heights) - i)) return maxArea diff --git a/python/846-Hand-of-Straights.py b/python/846-Hand-of-Straights.py index 9f31c956b..218bbf2f4 100644 --- a/python/846-Hand-of-Straights.py +++ b/python/846-Hand-of-Straights.py @@ -2,11 +2,11 @@ class Solution: def isNStraightHand(self, hand: List[int], groupSize: int) -> bool: if len(hand) % groupSize: return False - + count = {} for n in hand: count[n] = 1 + count.get(n, 0) - + minH = list(count.keys()) heapq.heapify(minH) while minH: @@ -19,4 +19,4 @@ def isNStraightHand(self, hand: List[int], groupSize: int) -> bool: if i != minH[0]: return False heapq.heappop(minH) - return True + return True diff --git a/python/853-Car-Fleet.py b/python/853-Car-Fleet.py index 40474898a..6ca875d26 100644 --- a/python/853-Car-Fleet.py +++ b/python/853-Car-Fleet.py @@ -3,7 +3,7 @@ def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: pair = [(p, s) for p, s in zip(position, speed)] pair.sort(reverse=True) stack = [] - for p, s in pair: # Reverse Sorted Order + for p, s in pair: # Reverse Sorted Order stack.append((target - p) / s) if len(stack) >= 2 and stack[-1] <= stack[-2]: stack.pop() diff --git a/python/875-Koko-Eating-Bananas.py b/python/875-Koko-Eating-Bananas.py index cfb701141..1d4bcf2a6 100644 --- a/python/875-Koko-Eating-Bananas.py +++ b/python/875-Koko-Eating-Bananas.py @@ -2,13 +2,13 @@ class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: l, r = 1, max(piles) k = 0 - + while l <= r: m = (l + r) // 2 - + totalTime = 0 for p in piles: - totalTime += ((p-1)//m) + 1 + totalTime += ((p - 1) // m) + 1 if totalTime <= H: k = m r = m - 1 diff --git a/python/90-Subsets-II.py b/python/90-Subsets-II.py index b951812fb..0e0d95626 100644 --- a/python/90-Subsets-II.py +++ b/python/90-Subsets-II.py @@ -2,19 +2,20 @@ class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: res = [] nums.sort() - + def backtrack(i, subset): if i == len(nums): res.append(subset[::]) - return - + return + # All subsets that include nums[i] subset.append(nums[i]) backtrack(i + 1, subset) subset.pop() # All subsets that don't include nums[i] - while i + 1 < len(nums) and nums[i] == nums[i+1]: + while i + 1 < len(nums) and nums[i] == nums[i + 1]: i += 1 backtrack(i + 1, subset) + backtrack(0, []) return res diff --git a/python/909-Snakes-and-Ladders.py b/python/909-Snakes-and-Ladders.py index b2338d7f0..a2de34d21 100644 --- a/python/909-Snakes-and-Ladders.py +++ b/python/909-Snakes-and-Ladders.py @@ -2,6 +2,7 @@ class Solution: def snakesAndLadders(self, board: List[List[int]]) -> int: length = len(board) board.reverse() + def intToPos(square): r = (square - 1) // length c = (square - 1) % length @@ -9,8 +10,8 @@ def intToPos(square): c = length - 1 - c return [r, c] - q = deque() - q.append([1, 0]) # [square, moves] + q = deque() + q.append([1, 0]) # [square, moves] visit = set() while q: square, moves = q.popleft() diff --git a/python/91-Decode-ways.py b/python/91-Decode-ways.py index 9b7fbd28e..f5b4b5ada 100644 --- a/python/91-Decode-ways.py +++ b/python/91-Decode-ways.py @@ -1,30 +1,34 @@ class Solution: def numDecodings(self, s: str) -> int: # Memoization - dp = { len(s) : 1 } + dp = {len(s): 1} + def dfs(i): if i in dp: return dp[i] if s[i] == "0": return 0 - + res = dfs(i + 1) - if (i + 1 < len(s) and (s[i] == "1" or - s[i] == "2" and s[i + 1] in "0123456")): + if i + 1 < len(s) and ( + s[i] == "1" or s[i] == "2" and s[i + 1] in "0123456" + ): res += dfs(i + 2) dp[i] = res return res + return dfs(0) # Dynamic Programming - dp = { len(s) : 1 } + dp = {len(s): 1} for i in range(len(s) - 1, -1, -1): if s[i] == "0": dp[i] = 0 else: dp[i] = dp[i + 1] - if (i + 1 < len(s) and (s[i] == "1" or - s[i] == "2" and s[i + 1] in "0123456")): + if i + 1 < len(s) and ( + s[i] == "1" or s[i] == "2" and s[i + 1] in "0123456" + ): dp[i] += dp[i + 2] return dp[0] diff --git a/python/92-Reverse-Linked-List-II.py b/python/92-Reverse-Linked-List-II.py index 6a9676fb1..39a5273f4 100644 --- a/python/92-Reverse-Linked-List-II.py +++ b/python/92-Reverse-Linked-List-II.py @@ -1,12 +1,14 @@ class Solution: - def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: + def reverseBetween( + self, head: Optional[ListNode], left: int, right: int + ) -> Optional[ListNode]: dummy = ListNode(0, head) - + # 1) reach node at position "left" leftPrev, cur = dummy, head for i in range(left - 1): leftPrev, cur = cur, cur.next - + # Now cur="left", leftPrev="node before left" # 2) reverse from left to right prev = None @@ -14,8 +16,8 @@ def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Opt tmpNext = cur.next cur.next = prev prev, cur = cur, tmpNext - + # 3) Update pointers - leftPrev.next.next = cur # cur is node after "right" - leftPrev.next = prev # prev is "right" + leftPrev.next.next = cur # cur is node after "right" + leftPrev.next = prev # prev is "right" return dummy.next diff --git a/python/94-Binary-Tree-Inorder-Traversal.py b/python/94-Binary-Tree-Inorder-Traversal.py index 85ab49cc6..cb184a758 100644 --- a/python/94-Binary-Tree-Inorder-Traversal.py +++ b/python/94-Binary-Tree-Inorder-Traversal.py @@ -3,7 +3,7 @@ def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: # Iterative res, stack = [], [] cur = root - + while cur or stack: while cur: stack.append(cur) @@ -12,7 +12,7 @@ def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: res.append(cur.val) cur = cur.right return res - + # Recursive res = [] @@ -22,5 +22,6 @@ def helper(root): helper(root.left) res.append(root.val) helper(root.right) + helper(root) return res diff --git a/python/97-Interleaving-Strings.py b/python/97-Interleaving-Strings.py index 3a0a149d3..efb43ac60 100644 --- a/python/97-Interleaving-Strings.py +++ b/python/97-Interleaving-Strings.py @@ -2,10 +2,10 @@ class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool: if len(s1) + len(s2) != len(s3): return False - - dp = [ [False] * (len(s2) + 1) for i in range(len(s1) + 1)] + + dp = [[False] * (len(s2) + 1) for i in range(len(s1) + 1)] dp[len(s1)][len(s2)] = True - + for i in range(len(s1), -1, -1): for j in range(len(s2), -1, -1): if i < len(s1) and s1[i] == s3[i + j] and dp[i + 1][j]: diff --git a/python/973-K-Closest-Points-to-Origin.py b/python/973-K-Closest-Points-to-Origin.py index 1318017cf..11e7eb8a6 100644 --- a/python/973-K-Closest-Points-to-Origin.py +++ b/python/973-K-Closest-Points-to-Origin.py @@ -4,7 +4,7 @@ def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: for x, y in points: dist = (abs(x - 0) ** 2) + (abs(y - 0) ** 2) pts.append([dist, x, y]) - + res = [] heapq.heapify(pts) for i in range(k): diff --git a/python/98-Validate-Binary-Search-Tree.py b/python/98-Validate-Binary-Search-Tree.py index bdf5228be..c69cad8fc 100644 --- a/python/98-Validate-Binary-Search-Tree.py +++ b/python/98-Validate-Binary-Search-Tree.py @@ -6,14 +6,14 @@ # self.right = right class Solution: def isValidBST(self, root: TreeNode) -> bool: - def valid(node, left, right): if not node: return True if not (node.val < right and node.val > left): return False - - return (valid(node.left, left, node.val) and - valid(node.right, node.val, right)) - + + return valid(node.left, left, node.val) and valid( + node.right, node.val, right + ) + return valid(root, float("-inf"), float("inf")) diff --git a/python/981-Time-Based-Key-Value-Store.py b/python/981-Time-Based-Key-Value-Store.py index d762fd774..32e9fdb4c 100644 --- a/python/981-Time-Based-Key-Value-Store.py +++ b/python/981-Time-Based-Key-Value-Store.py @@ -1,11 +1,10 @@ class TimeMap: - def __init__(self): """ Initialize your data structure here. """ - self.keyStore = {} # key : list of [val, timestamp] - + self.keyStore = {} # key : list of [val, timestamp] + def set(self, key: str, value: str, timestamp: int) -> None: if key not in self.keyStore: self.keyStore[key] = [] diff --git a/python/994-Rotting-Oranges.py b/python/994-Rotting-Oranges.py index 0f9afce04..5dbd76f29 100644 --- a/python/994-Rotting-Oranges.py +++ b/python/994-Rotting-Oranges.py @@ -3,27 +3,29 @@ def orangesRotting(self, grid: List[List[int]]) -> int: q = collections.deque() fresh = 0 time = 0 - + for r in range(len(grid)): for c in range(len(grid[0])): if grid[r][c] == 1: fresh += 1 if grid[r][c] == 2: q.append((r, c)) - + directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] while fresh > 0 and q: length = len(q) for i in range(length): r, c = q.popleft() - + for dr, dc in directions: row, col = r + dr, c + dc # if in bounds and nonrotten, make rotten # and add to q - if row in range(len(grid)) and \ - col in range(len(grid[0])) and \ - grid[row][col] == 1: + if ( + row in range(len(grid)) + and col in range(len(grid[0])) + and grid[row][col] == 1 + ): grid[row][col] = 2 q.append((row, col)) fresh -= 1 diff --git a/ruby/104-Maximum-Depth-of-Binary-Tree.rb b/ruby/104-Maximum-Depth-of-Binary-Tree.rb index 816fd42c6..da85a3d51 100644 --- a/ruby/104-Maximum-Depth-of-Binary-Tree.rb +++ b/ruby/104-Maximum-Depth-of-Binary-Tree.rb @@ -2,7 +2,7 @@ def max_depth(root) return 0 if root.nil? return 1 if root.left.nil? && root.right.nil? - left = 1 + max_depth(root.left) + left = 1 + max_depth(root.left) right = 1 + max_depth(root.right) left > right ? left : right end diff --git a/ruby/1046-Last-Stone-Weight.rb b/ruby/1046-Last-Stone-Weight.rb index d919c8b53..0e243f4d9 100644 --- a/ruby/1046-Last-Stone-Weight.rb +++ b/ruby/1046-Last-Stone-Weight.rb @@ -1,5 +1,5 @@ -require 'rubygems' -require 'algorithms' +require "rubygems" +require "algorithms" include Containers def last_stone_weight(stones) diff --git a/ruby/155-Min-Stack.rb b/ruby/155-Min-Stack.rb index 9f62c9560..72b6a758a 100644 --- a/ruby/155-Min-Stack.rb +++ b/ruby/155-Min-Stack.rb @@ -5,10 +5,10 @@ def initialize def push(val) min = if @stack.empty? - val - else - val < @stack.last[1] ? val : @stack.last[1] - end + val + else + val < @stack.last[1] ? val : @stack.last[1] + end @stack << [val, min] nil diff --git a/ruby/20-Valid-Parentheses.rb b/ruby/20-Valid-Parentheses.rb index ce364ea32..e140c5589 100644 --- a/ruby/20-Valid-Parentheses.rb +++ b/ruby/20-Valid-Parentheses.rb @@ -1,9 +1,9 @@ def is_valid(s) paren = [] match = { - '{' => '}', - '(' => ')', - '[' => ']' + "{" => "}", + "(" => ")", + "[" => "]", } s.each_char do |char| if match.key?(char) diff --git a/ruby/200-Number-of-Islands.rb b/ruby/200-Number-of-Islands.rb index 4ce588420..1ca4455ed 100644 --- a/ruby/200-Number-of-Islands.rb +++ b/ruby/200-Number-of-Islands.rb @@ -5,7 +5,7 @@ def num_islands(grid) memo = Array.new(grid.length) { Array.new(grid[0].length) } grid.each_with_index do |row, y| row.each_with_index do |el, x| - if memo[y][x].nil? && el == '1' + if memo[y][x].nil? && el == "1" islands += 1 flood_fill(grid, memo, y, x) end @@ -15,10 +15,10 @@ def num_islands(grid) end def flood_fill(grid, memo, y, x) - return nil if y >= grid.length || y.negative? || + return nil if y >= grid.length || y.negative? || x >= grid[0].length || x.negative? || memo[y][x] != nil || - grid[y][x] == '0' + grid[y][x] == "0" memo[y][x] = true DIRS.each do |dy, dx| diff --git a/ruby/206-Reverse-Linked-List.rb b/ruby/206-Reverse-Linked-List.rb index 148c5e5a2..d6dde7a93 100644 --- a/ruby/206-Reverse-Linked-List.rb +++ b/ruby/206-Reverse-Linked-List.rb @@ -13,7 +13,7 @@ def reverse_list(head) end end -# Recursive +# Recursive def reverse_list(head) return head if head.nil? diff --git a/ruby/208-Implement-Trie.rb b/ruby/208-Implement-Trie.rb index 0d756812a..770246847 100644 --- a/ruby/208-Implement-Trie.rb +++ b/ruby/208-Implement-Trie.rb @@ -1,5 +1,5 @@ class Trie - END_OF_WORD = 'END' + END_OF_WORD = "END" def initialize @root = {} diff --git a/ruby/338-Counting-Bits.rb b/ruby/338-Counting-Bits.rb index e8f4bd8f6..802567144 100644 --- a/ruby/338-Counting-Bits.rb +++ b/ruby/338-Counting-Bits.rb @@ -3,10 +3,10 @@ def count_bits(n) offset = 2 (n + 1).times do |nbr| bits << if nbr <= 2 || nbr == (offset * 2) - nbr.zero? ? 0 : 1 - else - (bits[offset] + bits[nbr - offset]) - end + nbr.zero? ? 0 : 1 + else + (bits[offset] + bits[nbr - offset]) + end offset *= 2 if nbr == offset * 2 end diff --git a/ruby/36-Valid-Sudoku.rb b/ruby/36-Valid-Sudoku.rb index 3198bd987..634752ec2 100644 --- a/ruby/36-Valid-Sudoku.rb +++ b/ruby/36-Valid-Sudoku.rb @@ -18,7 +18,7 @@ def valid_rows_and_columns?(board) def valid?(row) hash = {} row.each do |cell| - next if cell == '.' + next if cell == "." return false if hash.key? cell hash[cell] = true diff --git a/ruby/70-Climbing-Stairs.rb b/ruby/70-Climbing-Stairs.rb index 033a40808..98968588a 100644 --- a/ruby/70-Climbing-Stairs.rb +++ b/ruby/70-Climbing-Stairs.rb @@ -8,6 +8,7 @@ def climb_stairs(n) # Memoize $repeat = [] + def climb_stairs(n) return 1 if n.zero? return 0 if n.negative? diff --git a/ruby/703-Kth-Largest-Element-in-a-Stream.rb b/ruby/703-Kth-Largest-Element-in-a-Stream.rb index 78a5ca624..dda9c8365 100644 --- a/ruby/703-Kth-Largest-Element-in-a-Stream.rb +++ b/ruby/703-Kth-Largest-Element-in-a-Stream.rb @@ -1,4 +1,4 @@ -require 'rb_heap' +require "rb_heap" class KthLargest def initialize(k, nums) diff --git a/ruby/746-Min-Cost-Climbing-Stairs.rb b/ruby/746-Min-Cost-Climbing-Stairs.rb index 159a17eeb..5fe7f960b 100644 --- a/ruby/746-Min-Cost-Climbing-Stairs.rb +++ b/ruby/746-Min-Cost-Climbing-Stairs.rb @@ -5,7 +5,7 @@ def min_cost_climbing_stairs(cost) second = 0 first = cost[-1] (cost.length - 2).downto(0) do |idx| - cost1 = cost[idx] + first + cost1 = cost[idx] + first cost2 = cost[idx] + second tmp = cost1 > cost2 ? cost2 : cost1 second = first diff --git a/typescript/1-Two-Sum.ts b/typescript/1-Two-Sum.ts index 841da2c13..73fba22ee 100644 --- a/typescript/1-Two-Sum.ts +++ b/typescript/1-Two-Sum.ts @@ -1,11 +1,11 @@ function twoSum(nums: number[], target: number): number[] { - let hash: { [key: number]: number } = {} + let hash: { [key: number]: number } = {}; for (let i = 0; i < nums.length; i++) { - let diff = target - nums[i] + let diff = target - nums[i]; if (diff in hash) { - return [hash[diff], i] + return [hash[diff], i]; } else { - hash[nums[i]] = i + hash[nums[i]] = i; } } } diff --git a/typescript/110-Balanced-Binary-Tree.ts b/typescript/110-Balanced-Binary-Tree.ts index baa990c19..331d05d50 100644 --- a/typescript/110-Balanced-Binary-Tree.ts +++ b/typescript/110-Balanced-Binary-Tree.ts @@ -23,7 +23,8 @@ function getHeight(root: TreeNode | null) { let [leftBalanced, leftHeight] = getHeight(root.left); let [rightBalanced, rightHeight] = getHeight(root.right); - let balanced = leftBalanced && rightBalanced && Math.abs(rightHeight - leftHeight) <= 1; + let balanced = + leftBalanced && rightBalanced && Math.abs(rightHeight - leftHeight) <= 1; return [balanced, 1 + Math.max(leftHeight, rightHeight)]; } diff --git a/typescript/1143-Longest-Common-Subsequence.ts b/typescript/1143-Longest-Common-Subsequence.ts index 31af83176..ae3da3dc8 100644 --- a/typescript/1143-Longest-Common-Subsequence.ts +++ b/typescript/1143-Longest-Common-Subsequence.ts @@ -1,20 +1,20 @@ function longestCommonSubsequence(text1: string, text2: string): number { - let temp: number[][] = [] - let max: number = 0 + let temp: number[][] = []; + let max: number = 0; for (let i = 0; i <= text1.length; i++) { - temp.push(new Array(text2.length + 1).fill(0)) + temp.push(new Array(text2.length + 1).fill(0)); } for (let i = 1; i < temp.length; i++) { for (let j = 1; j < temp[0].length; j++) { if (text1[i - 1] === text2[j - 1]) { - temp[i][j] = temp[i - 1][j - 1] + 1 + temp[i][j] = temp[i - 1][j - 1] + 1; } else { - temp[i][j] = Math.max(temp[i - 1][j], temp[i][j - 1]) + temp[i][j] = Math.max(temp[i - 1][j], temp[i][j - 1]); } - max = Math.max(max, temp[i][j]) + max = Math.max(max, temp[i][j]); } } - return max + return max; } diff --git a/typescript/125-Valid-Palindrome.ts b/typescript/125-Valid-Palindrome.ts index a1f7736ce..1a26c22e0 100644 --- a/typescript/125-Valid-Palindrome.ts +++ b/typescript/125-Valid-Palindrome.ts @@ -1,5 +1,9 @@ function isPalindrome(s: string): boolean { - const array = s.toLowerCase().replace(/[^A-Za-z0-9]/g, "").replace(/\s/g, "").split(""); + const array = s + .toLowerCase() + .replace(/[^A-Za-z0-9]/g, '') + .replace(/\s/g, '') + .split(''); for (let i = 0; i < array.length; i++) { const first = array[i]; @@ -10,4 +14,4 @@ function isPalindrome(s: string): boolean { } } return true; -} \ No newline at end of file +} diff --git a/typescript/150-Evaluate-Reverse-Polish-Notation.ts b/typescript/150-Evaluate-Reverse-Polish-Notation.ts index 166ff2304..6d3230a04 100644 --- a/typescript/150-Evaluate-Reverse-Polish-Notation.ts +++ b/typescript/150-Evaluate-Reverse-Polish-Notation.ts @@ -2,17 +2,17 @@ function evalRPN(tokens: string[]): number { const stack: number[] = []; tokens.forEach((token) => { - if (token === "+") { + if (token === '+') { stack.push(Number(stack.pop()) + Number(stack.pop())); - } else if (token === "-") { + } else if (token === '-') { const a = Number(stack.pop()); const b = Number(stack.pop()); stack.push(b - a); - } else if (token === "/") { + } else if (token === '/') { const a = Number(stack.pop()); const b = Number(stack.pop()); stack.push(Math.trunc(b / a)); - } else if (token === "*") { + } else if (token === '*') { stack.push(Number(stack.pop()) * Number(stack.pop())); } else { stack.push(Number(token)); diff --git a/typescript/153-Find-Minimum-in-Rotated-Sorted-Array.ts b/typescript/153-Find-Minimum-in-Rotated-Sorted-Array.ts index 065ea3020..30d488670 100644 --- a/typescript/153-Find-Minimum-in-Rotated-Sorted-Array.ts +++ b/typescript/153-Find-Minimum-in-Rotated-Sorted-Array.ts @@ -1,13 +1,13 @@ function findMin(nums: number[]): number { - let left: number = 0 - let right: number = nums.length - 1 + let left: number = 0; + let right: number = nums.length - 1; while (right > left) { - let midIdx: number = Math.floor((left + right) / 2) + let midIdx: number = Math.floor((left + right) / 2); if (nums[midIdx] > nums[right]) { - left = midIdx + 1 + left = midIdx + 1; } else { - right = midIdx + right = midIdx; } } - return nums[left] + return nums[left]; } diff --git a/typescript/17-Letter-Combinations-of-a-Phone-Number.ts b/typescript/17-Letter-Combinations-of-a-Phone-Number.ts index cd347efc5..b54150a79 100644 --- a/typescript/17-Letter-Combinations-of-a-Phone-Number.ts +++ b/typescript/17-Letter-Combinations-of-a-Phone-Number.ts @@ -2,14 +2,14 @@ function letterCombinations(digits: string): string[] { let res: string[] = []; const digitToChar = { - "2": "abc", - "3": "def", - "4": "ghi", - "5": "jkl", - "6": "mno", - "7": "qprs", - "8": "tuv", - "9": "wxyz", + '2': 'abc', + '3': 'def', + '4': 'ghi', + '5': 'jkl', + '6': 'mno', + '7': 'qprs', + '8': 'tuv', + '9': 'wxyz', }; function backtrack(i: number, curStr: string) { @@ -24,7 +24,7 @@ function letterCombinations(digits: string): string[] { } if (digits) { - backtrack(0, ""); + backtrack(0, ''); } return res; diff --git a/typescript/19-Remove-Nth-Node-From-End-of-List.ts b/typescript/19-Remove-Nth-Node-From-End-of-List.ts index 24268c9fb..e8045142d 100644 --- a/typescript/19-Remove-Nth-Node-From-End-of-List.ts +++ b/typescript/19-Remove-Nth-Node-From-End-of-List.ts @@ -11,21 +11,21 @@ */ function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { - let dummy: ListNode = new ListNode(0, head) - let left = dummy - let right = head - - while (n > 0) { - right = right.next - n -= 1 - } - - while (right) { - left = left.next - right = right.next - } - - // delete - left.next = left.next.next - return dummy.next -}; + let dummy: ListNode = new ListNode(0, head); + let left = dummy; + let right = head; + + while (n > 0) { + right = right.next; + n -= 1; + } + + while (right) { + left = left.next; + right = right.next; + } + + // delete + left.next = left.next.next; + return dummy.next; +} diff --git a/typescript/191-Number-of-1-Bits.ts b/typescript/191-Number-of-1-Bits.ts index 72866886f..426665e0d 100644 --- a/typescript/191-Number-of-1-Bits.ts +++ b/typescript/191-Number-of-1-Bits.ts @@ -1,9 +1,9 @@ function hammingWeight(n: number): number { - let base2 = n.toString(2).split(""); + let base2 = n.toString(2).split(''); let count = 0; base2.forEach((item) => { - if (item === "1") { + if (item === '1') { count += 1; } }); diff --git a/typescript/2-Add-Two-Numbers.ts b/typescript/2-Add-Two-Numbers.ts index ca29afe41..8152928aa 100644 --- a/typescript/2-Add-Two-Numbers.ts +++ b/typescript/2-Add-Two-Numbers.ts @@ -14,24 +14,24 @@ function addTwoNumbers( l1: ListNode | null, l2: ListNode | null ): ListNode | null { - let dummyNode: ListNode = new ListNode() - let currentNode: ListNode = dummyNode - let carry: number = 0 + let dummyNode: ListNode = new ListNode(); + let currentNode: ListNode = dummyNode; + let carry: number = 0; while (l1 !== null || l2 !== null || carry !== 0) { - const val1 = l1 !== null ? l1.val : 0 - const val2 = l2 !== null ? l2.val : 0 + const val1 = l1 !== null ? l1.val : 0; + const val2 = l2 !== null ? l2.val : 0; - const sum: number = val1 + val2 + carry - const value: number = sum % 10 - const newLinkedList: ListNode = new ListNode(value) - currentNode.next = newLinkedList - currentNode = newLinkedList - carry = Math.floor(sum / 10) + const sum: number = val1 + val2 + carry; + const value: number = sum % 10; + const newLinkedList: ListNode = new ListNode(value); + currentNode.next = newLinkedList; + currentNode = newLinkedList; + carry = Math.floor(sum / 10); - l1 = l1 !== null ? l1.next : null - l2 = l2 !== null ? l2.next : null + l1 = l1 !== null ? l1.next : null; + l2 = l2 !== null ? l2.next : null; } - return dummyNode.next + return dummyNode.next; } diff --git a/typescript/20-Valid-Parentheses.ts b/typescript/20-Valid-Parentheses.ts index bf817cdcc..ce6388132 100644 --- a/typescript/20-Valid-Parentheses.ts +++ b/typescript/20-Valid-Parentheses.ts @@ -1,11 +1,11 @@ function isValid(s: string): boolean { const closingToOpening = { - "}": "{", - "]": "[", - ")": "(", + '}': '{', + ']': '[', + ')': '(', }; const stack: string[] = []; - const chars = s.split(""); + const chars = s.split(''); for (let i = 0; i < chars.length; i++) { const element = chars[i]; diff --git a/typescript/206-Reverse-Linked-List.ts b/typescript/206-Reverse-Linked-List.ts index 4fe6525a9..792b7e1e8 100644 --- a/typescript/206-Reverse-Linked-List.ts +++ b/typescript/206-Reverse-Linked-List.ts @@ -11,13 +11,13 @@ */ function reverseList(head: ListNode | null): ListNode | null { - let prev: ListNode | null = null + let prev: ListNode | null = null; while (head) { - let ele = head.next - head.next = prev - prev = head - head = ele + let ele = head.next; + head.next = prev; + prev = head; + head = ele; } - return prev + return prev; } diff --git a/typescript/208-Implement-Trie.ts b/typescript/208-Implement-Trie.ts index c4b6aeec7..25c15196a 100644 --- a/typescript/208-Implement-Trie.ts +++ b/typescript/208-Implement-Trie.ts @@ -53,9 +53,9 @@ class Trie { } const trie = new Trie(); -trie.insert("apple"); -trie.search("apple"); // return True -trie.search("app"); // return False -trie.startsWith("app"); // return True -trie.insert("app"); -trie.search("app"); // return True +trie.insert('apple'); +trie.search('apple'); // return True +trie.search('app'); // return False +trie.startsWith('app'); // return True +trie.insert('app'); +trie.search('app'); // return True diff --git a/typescript/21-Merge-Two-Sorted-Lists.ts b/typescript/21-Merge-Two-Sorted-Lists.ts index 5ce0827e7..6f12d7340 100644 --- a/typescript/21-Merge-Two-Sorted-Lists.ts +++ b/typescript/21-Merge-Two-Sorted-Lists.ts @@ -14,23 +14,23 @@ function mergeTwoLists( list1: ListNode | null, list2: ListNode | null ): ListNode | null { - let dummyList: ListNode = new ListNode(0) - let currentNode: ListNode = dummyList + let dummyList: ListNode = new ListNode(0); + let currentNode: ListNode = dummyList; while (list1 !== null && list2 !== null) { if (list1.val < list2.val) { - currentNode.next = list1 - list1 = list1.next + currentNode.next = list1; + list1 = list1.next; } else { - currentNode.next = list2 - list2 = list2.next + currentNode.next = list2; + list2 = list2.next; } - currentNode = currentNode.next + currentNode = currentNode.next; } - if (list1 !== null) currentNode.next = list1 - if (list2 !== null) currentNode.next = list2 + if (list1 !== null) currentNode.next = list1; + if (list2 !== null) currentNode.next = list2; - return dummyList.next + return dummyList.next; } diff --git a/typescript/211-Design-Add-and-Search-Words-Data-Structure.ts b/typescript/211-Design-Add-and-Search-Words-Data-Structure.ts index 3e92596ae..7c239b593 100644 --- a/typescript/211-Design-Add-and-Search-Words-Data-Structure.ts +++ b/typescript/211-Design-Add-and-Search-Words-Data-Structure.ts @@ -32,7 +32,7 @@ class WordDictionary { for (let i = j; i < word.length; i++) { const c = word[i]; - if (c === ".") { + if (c === '.') { for (const key in cur.children) { if (Object.prototype.hasOwnProperty.call(cur.children, key)) { const child = cur.children[key]; diff --git a/typescript/22-Generate-Parentheses.ts b/typescript/22-Generate-Parentheses.ts index 13d2358b2..6783cb7c3 100644 --- a/typescript/22-Generate-Parentheses.ts +++ b/typescript/22-Generate-Parentheses.ts @@ -4,18 +4,18 @@ function generateParenthesis(n: number): string[] { function backtrack(openN: number, closedN: number) { if (openN === n && closedN === n) { - res.push(stack.join("")); + res.push(stack.join('')); return; } if (openN < n) { - stack.push("("); + stack.push('('); backtrack(openN + 1, closedN); stack.pop(); } if (closedN < openN) { - stack.push(")"); + stack.push(')'); backtrack(openN, closedN + 1); stack.pop(); } diff --git a/typescript/235-Lowest-Common-Ancestor-of-a-Binary Search-Tree.ts b/typescript/235-Lowest-Common-Ancestor-of-a-Binary Search-Tree.ts index e092dd80f..141942cac 100644 --- a/typescript/235-Lowest-Common-Ancestor-of-a-Binary Search-Tree.ts +++ b/typescript/235-Lowest-Common-Ancestor-of-a-Binary Search-Tree.ts @@ -12,7 +12,11 @@ * } */ -function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null ): TreeNode | null { +function lowestCommonAncestor( + root: TreeNode | null, + p: TreeNode | null, + q: TreeNode | null +): TreeNode | null { let cur = root; while (cur) { diff --git a/typescript/238-Product-of-Array-Except-Self.ts b/typescript/238-Product-of-Array-Except-Self.ts index 851ae5d65..8fa4d93ee 100644 --- a/typescript/238-Product-of-Array-Except-Self.ts +++ b/typescript/238-Product-of-Array-Except-Self.ts @@ -1,18 +1,18 @@ function productExceptSelf(nums: number[]): number[] { - const array: Array = [] - let product: number = 1 + const array: Array = []; + let product: number = 1; for (let idx = 0; idx < nums.length; idx++) { - array[idx] = product - product *= nums[idx] + array[idx] = product; + product *= nums[idx]; } - product = 1 + product = 1; for (let idx = nums.length - 1; idx >= 0; idx--) { - array[idx] *= product - product *= nums[idx] + array[idx] *= product; + product *= nums[idx]; } - return array + return array; } diff --git a/typescript/242-Valid-Anagram.ts b/typescript/242-Valid-Anagram.ts index a38912fc6..1c7b5e2a9 100644 --- a/typescript/242-Valid-Anagram.ts +++ b/typescript/242-Valid-Anagram.ts @@ -1,8 +1,8 @@ function isAnagram(s: string, t: string) { if (s.length !== t.length) return false; - let first: Array = s.split(""); - const second = t.split(""); + let first: Array = s.split(''); + const second = t.split(''); for (let i = 0; i < second.length; i++) { const element = second[i]; diff --git a/typescript/261-Graph-Valid-Tree.ts b/typescript/261-Graph-Valid-Tree.ts index 4cf62c3a5..6bd391ce5 100644 --- a/typescript/261-Graph-Valid-Tree.ts +++ b/typescript/261-Graph-Valid-Tree.ts @@ -1,27 +1,27 @@ interface Obj { - [key: number]: Array + [key: number]: Array; } interface Visited { - [key: number]: boolean + [key: number]: boolean; } function validTree(n: number, edges: number[][]): boolean { - if (n === 0) return true + if (n === 0) return true; - let adjacent: Obj = {} - let visited: Visited = {} + let adjacent: Obj = {}; + let visited: Visited = {}; for (let i = 0; i < n; i++) { - adjacent[i] = [] + adjacent[i] = []; } for (const val of edges) { - const [n1, n2] = val - adjacent[n1].push(n2) - adjacent[n2].push(n1) + const [n1, n2] = val; + adjacent[n1].push(n2); + adjacent[n2].push(n1); } - return dfs(0, -1, visited, adjacent) && Object.keys(visited).length === n + return dfs(0, -1, visited, adjacent) && Object.keys(visited).length === n; } function dfs( @@ -30,13 +30,13 @@ function dfs( visited: Visited, adjacent: Obj ): boolean { - if (visited[node]) return false - visited[node] = true + if (visited[node]) return false; + visited[node] = true; for (const ele of adjacent[node]) { - if (ele === prevNode) continue - if (!dfs(ele, node, visited, adjacent)) return false + if (ele === prevNode) continue; + if (!dfs(ele, node, visited, adjacent)) return false; } - return true + return true; } diff --git a/typescript/268-Missing-Number.ts b/typescript/268-Missing-Number.ts index c973f52ea..ceb92fea4 100644 --- a/typescript/268-Missing-Number.ts +++ b/typescript/268-Missing-Number.ts @@ -1,8 +1,8 @@ function missingNumber(nums: number[]): number { - let sum: number = 0 - let total: number = (nums.length * (nums.length + 1)) / 2 + let sum: number = 0; + let total: number = (nums.length * (nums.length + 1)) / 2; for (let i = 0; i < nums.length; i++) { - sum += nums[i] + sum += nums[i]; } - return total - sum + return total - sum; } diff --git a/typescript/33-Search-in-Rotated-Sorted-Array.ts b/typescript/33-Search-in-Rotated-Sorted-Array.ts index 0612f2a1d..ad02f99b6 100644 --- a/typescript/33-Search-in-Rotated-Sorted-Array.ts +++ b/typescript/33-Search-in-Rotated-Sorted-Array.ts @@ -1,18 +1,18 @@ function search(nums: number[], target: number): number { - let left: number = 0 - let right: number = nums.length - 1 + let left: number = 0; + let right: number = nums.length - 1; while (left <= right) { - let midIdx: number = Math.floor((left + right) / 2) - if (nums[midIdx] === target) return midIdx + let midIdx: number = Math.floor((left + right) / 2); + if (nums[midIdx] === target) return midIdx; if (nums[left] <= nums[midIdx]) { - if (nums[left] <= target && target <= nums[midIdx]) right = midIdx - 1 - else left = midIdx + 1 + if (nums[left] <= target && target <= nums[midIdx]) right = midIdx - 1; + else left = midIdx + 1; } else { - if (nums[midIdx] <= target && target <= nums[right]) left = midIdx + 1 - else right = midIdx - 1 + if (nums[midIdx] <= target && target <= nums[right]) left = midIdx + 1; + else right = midIdx - 1; } } - return -1 + return -1; } diff --git a/typescript/338-Counting-Bits.ts b/typescript/338-Counting-Bits.ts index 6a32a874f..b6e230e11 100644 --- a/typescript/338-Counting-Bits.ts +++ b/typescript/338-Counting-Bits.ts @@ -9,11 +9,11 @@ function countBits(n: number): number[] { } function hammingWeight(n: number): number { - let base2 = n.toString(2).split(""); + let base2 = n.toString(2).split(''); let count = 0; base2.forEach((item) => { - if (item === "1") { + if (item === '1') { count += 1; } }); diff --git a/typescript/36-Valid-Sudoku.ts b/typescript/36-Valid-Sudoku.ts index bb370a209..b37326047 100644 --- a/typescript/36-Valid-Sudoku.ts +++ b/typescript/36-Valid-Sudoku.ts @@ -7,7 +7,7 @@ function isValidSudoku(board: string[][]): boolean { for (let c = 0; c < 9; c++) { const num = board[r][c]; - if (num === ".") { + if (num === '.') { continue; } diff --git a/typescript/43-Multiply-Strings.ts b/typescript/43-Multiply-Strings.ts index 3e8d9b5df..40514b542 100644 --- a/typescript/43-Multiply-Strings.ts +++ b/typescript/43-Multiply-Strings.ts @@ -1,21 +1,21 @@ function multiply(num1: string, num2: string): string { - if (num1 === "0" || num2 === "0") { - return "0" + if (num1 === '0' || num2 === '0') { + return '0'; } - let maxLength: number = num1.length + num2.length - let result: Array = Array(maxLength).fill(0) + let maxLength: number = num1.length + num2.length; + let result: Array = Array(maxLength).fill(0); for (let i = num2.length - 1; i >= 0; i--) { - let idx = maxLength - (num2.length - i) + let idx = maxLength - (num2.length - i); for (let j = num1.length - 1; j >= 0; j--) { const product = - result[idx] + parseInt(num1.charAt(j)) * parseInt(num2.charAt(i)) - result[idx] = Math.floor(product % 10) - result[idx - 1] = Math.floor(product / 10) + result[idx - 1] - idx-- + result[idx] + parseInt(num1.charAt(j)) * parseInt(num2.charAt(i)); + result[idx] = Math.floor(product % 10); + result[idx - 1] = Math.floor(product / 10) + result[idx - 1]; + idx--; } } - if (result[0] === 0) return result.slice(1).join("") - else return result.join("") + if (result[0] === 0) return result.slice(1).join(''); + else return result.join(''); } diff --git a/typescript/49-Group-Anagrams.ts b/typescript/49-Group-Anagrams.ts index 532794768..839fbd79e 100644 --- a/typescript/49-Group-Anagrams.ts +++ b/typescript/49-Group-Anagrams.ts @@ -22,13 +22,13 @@ function groupAnagrams(strs: string[]): string[][] { return [...Object.keys(hash).map((k) => hash[k])]; } -console.log(groupAnagrams(["eat", "ate", "dog", "pog"])); +console.log(groupAnagrams(['eat', 'ate', 'dog', 'pog'])); function isAnagram(s: string, t: string) { if (s.length !== t.length) return false; - var first: Array = s.split(""); - const second = t.split(""); + var first: Array = s.split(''); + const second = t.split(''); for (let i = 0; i < second.length; i++) { const element = second[i]; diff --git a/typescript/5-Longest-Palindromic-Substring.ts b/typescript/5-Longest-Palindromic-Substring.ts index 491db9c40..48aa360bb 100644 --- a/typescript/5-Longest-Palindromic-Substring.ts +++ b/typescript/5-Longest-Palindromic-Substring.ts @@ -1,5 +1,5 @@ function longestPalindrome(s: string): string { - let res = ""; + let res = ''; let resLen = 0; for (let i = 0; i < s.length; i++) { diff --git a/typescript/567-Permutation-in-String.ts b/typescript/567-Permutation-in-String.ts index b66459a94..b43c85e39 100644 --- a/typescript/567-Permutation-in-String.ts +++ b/typescript/567-Permutation-in-String.ts @@ -5,8 +5,8 @@ function checkInclusion(s1: string, s2: string): boolean { const s2Count = Array(26).fill(0); for (let i = 0; i < s1.length; i++) { - s1Count[s1[i].charCodeAt(0) - "a".charCodeAt(0)] += 1; - s2Count[s2[i].charCodeAt(0) - "a".charCodeAt(0)] += 1; + s1Count[s1[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; + s2Count[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; } let matches = 0; @@ -20,7 +20,7 @@ function checkInclusion(s1: string, s2: string): boolean { for (let r = s1.length; r < s2.length; r++) { if (matches == 26) return true; - let index = s2[r].charCodeAt(0) - "a".charCodeAt(0); + let index = s2[r].charCodeAt(0) - 'a'.charCodeAt(0); s2Count[index] += 1; if (s1Count[index] == s2Count[index]) { matches += 1; @@ -28,7 +28,7 @@ function checkInclusion(s1: string, s2: string): boolean { matches -= 1; } - let index2 = s2[l].charCodeAt(0) - "a".charCodeAt(0); + let index2 = s2[l].charCodeAt(0) - 'a'.charCodeAt(0); s2Count[index2] -= 1; if (s1Count[index2] == s2Count[index2]) { matches += 1; diff --git a/typescript/66-Plus-One.ts b/typescript/66-Plus-One.ts index 9d0df0bab..3f7848805 100644 --- a/typescript/66-Plus-One.ts +++ b/typescript/66-Plus-One.ts @@ -1,6 +1,6 @@ function plusOne(digits: number[]): number[] { - return (BigInt(digits.join("")) + BigInt(1)) + return (BigInt(digits.join('')) + BigInt(1)) .toString() - .split("") + .split('') .map((item) => Number(item)); } diff --git a/typescript/7-Reverse-Integer.ts b/typescript/7-Reverse-Integer.ts index ed4c52489..49e2774b0 100644 --- a/typescript/7-Reverse-Integer.ts +++ b/typescript/7-Reverse-Integer.ts @@ -1,23 +1,23 @@ -const reverse = (x: number): number => { - const max: number = 2 ** 31 - 1; - const min: number = -(2 ** 31); - - let result: number = 0; - while (x !== 0) { - const digit = x % 10; - x = Math.trunc(x / 10); - - if (result > max / 10 || (result === max / 10 && digit >= max % 10)) { - return 0; - } else if ( - result < min / 10 || - (result === max / 10 && digit <= min % 10) - ) { - return 0; - } else { - result = result * 10 + digit; - } - } - - return result; - }; \ No newline at end of file +const reverse = (x: number): number => { + const max: number = 2 ** 31 - 1; + const min: number = -(2 ** 31); + + let result: number = 0; + while (x !== 0) { + const digit = x % 10; + x = Math.trunc(x / 10); + + if (result > max / 10 || (result === max / 10 && digit >= max % 10)) { + return 0; + } else if ( + result < min / 10 || + (result === max / 10 && digit <= min % 10) + ) { + return 0; + } else { + result = result * 10 + digit; + } + } + + return result; +}; diff --git a/typescript/9-Palindrome-Number.ts b/typescript/9-Palindrome-Number.ts index 47445dc26..e64dcb22f 100644 --- a/typescript/9-Palindrome-Number.ts +++ b/typescript/9-Palindrome-Number.ts @@ -1,13 +1,13 @@ -var isPalindrome = (x: number) => { - // Creates array from int characters - // 121 -> [1,2,1] - let arr = Array.from(String(x), Number); - - // Uses two pointer - for (let i = 0; i < arr.length; i++) { - if (arr[i] !== arr[arr.length - 1 - i]) { - return false; - } - } - return true; -}; +var isPalindrome = (x: number) => { + // Creates array from int characters + // 121 -> [1,2,1] + let arr = Array.from(String(x), Number); + + // Uses two pointer + for (let i = 0; i < arr.length; i++) { + if (arr[i] !== arr[arr.length - 1 - i]) { + return false; + } + } + return true; +}; diff --git a/typescript/91-Decode-Ways.ts b/typescript/91-Decode-Ways.ts index e4337c1d0..358385bbf 100644 --- a/typescript/91-Decode-Ways.ts +++ b/typescript/91-Decode-Ways.ts @@ -4,14 +4,14 @@ function numDecodings(s: string): number { }; for (let i = s.length - 1; i > -1; i--) { - if (s[i] == "0") { + if (s[i] == '0') { dp[i] = 0; } else { dp[i] = dp[i + 1]; } if ( i + 1 < s.length && - (s[i] == "1" || (s[i] == "2" && "0123456".includes(s[i + 1]))) + (s[i] == '1' || (s[i] == '2' && '0123456'.includes(s[i + 1]))) ) { dp[i] += dp[i + 2]; }