If you like this project, please leave me a star. ★
The project is divided into two parts: structure
and solution
.
structure
package contains the data structure required for the question, such as TreeNode
for the binary tree question, ListNode
for the linked list question, etc.
solution
package contains the leetcode algorithm problems, packaged by solution type.
No. | Title | Short Description |
---|---|---|
1 | TreeNode | Definition for the Binary Tree node. - construct List by Integer Array. - print the Binary Tree with level order. |
2 | ListNode | Definition for the LinkedList node. - construct List by Integer Array. - construct by value. - set cycle(to solve the cycle problems). - print the LinkedList. |
3 | Node | Definition for the Tree node with next right pointers. - construct List by Integer Array. |
4 | NNode | Definition for the N-ary Tree node. - construct List by Integer Array. - construct by value. |
Tool class for handling issues such as format conversions.
No. | Title | Short Description |
---|---|---|
1 | InputUtils.java | Handle Input Data Format - java int[][] generateGrid(int m, int n, String s) : convert String like "[[0,1],[0,2]]" to grid. |
Reverse
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
92 | Reverse Linked List II | Medium | ReverseLinkedListII.java | Iteration | Recursion Reverse Linked List between a and b . At first, we can move to a-th, and the problem becomes Reverse Top N nodes. |
25 | Reverse Nodes in k-Group | Hard | ReverseNodesInkGroup.java | For each k group, reverse Linked List between head and k-th. Let head equal k+1th node, then do Recursion. |
234 | Palindrome Linked List | Easy | PalindromeLinkedList.java | 1. Using a pointer that points to the node from the start location. Recursion and move pointer forward. Compare. 2. Reverse the whole List. 3. Reverse the second-half List |
143 | Reorder List | Easy | ReorderList.java | Reverse the second-half List and Merge |
147 | Insertion Sort List | Easy | InsertionSortList.java | Virtual Head Node |
206 | Reverse Linked List | Easy | ReverseLinkedList.java | Iteration | Recursion |
2130 | Maximum Twin Sum of a Linked List | Medium | MaximumTwinSumOfALinkedList.java | Reverse the second-half List |
Two Pointer
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
160 | Intersection of Two Linked Lists | Easy | IntersectionOfTwoLinkedLists.java | Hash | A + B |
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
341 | Flatten Nested List Iterator | Medium | FlattenNestedListIterator.java | LinkedList, Deque, or Stack. |
348 | Design Tic-Tac-Toe | Medium | DesignTicTacToe.java | using Array. |
380 | Insert Delete GetRandom O(1) | Medium | InsertDeleteGetRandom.java | HashMap + ArrayList |
622 | Design Circular Queue | Medium | DesignCircularQueue.java | Using Array and Pointer. |
705 | Design HashSet | Easy | DesignHashSet.java | Array + LinkedList |
706 | Design HashMap | Easy | DesignHashMap.java | Array + LinkedList |
1166 | Design File System | Medium | DesignFileSystem.java | - 1. Trie: using HashMap as the child list. |
1396 | Design Underground System | Medium | DesignUndergroundSystem.java | using two HashMap. One saves the check-in record, another saves the data of the current stage. |
2102 | Sequentially Ordinal Rank Tracker | Hard | SequentiallyOrdinalRankTracker.java | Two Heap. |
Traversal
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
94 | Binary Tree Inorder Traversal | Easy | BinaryTreeInorderTraversal.java | Recursion and Iteration |
144 | Binary Tree Preorder Traversal | Easy | BinaryTreePreorderTraversal.java | Recursion and Iteration |
145 | Binary Tree Postorder Traversal | Easy | BinaryTreePostorderTraversal.java | Recursion and Iteration |
314 | Binary Tree Vertical Order Traversal | Medium | BinaryTreeVerticalOrderTraversal.java | Recursion and Iteration |
102 | Binary Tree Level Order Traversal | Medium | BinaryTreeLevelOrderTraversal.java | BFS |
Construct
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
Serialize and Deserialize
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
173 | Binary Search Tree Iterator | Medium | BinarySearchTreeIterator.java | |
230 | Kth Smallest Element in a BST | Medium | KthSmallestElementInABST.java | Preorder traversal |
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
222 | Count Complete Tree Nodes | Medium | CountCompleteTreeNodes.java | Consider left and right separatly |
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
17 | Letter Combinations of a Phone Number | Medium | LetterCombinationsPhoneNumber.java | Backtrack |
39 | Combination Sum | Medium | CombinationSum.java | Backtrack |
40 | Combination Sum II | Medium | CombinationSumII.java | Backtrack |
46 | Permutations | Medium | Permutations.java | Backtrack |
47 | Permutations II | Medium | PermutationsII.java | Backtrack |
51 | N-Queens | Hard | NQueens.java | Backtrack + Memo |
52 | N-Queens II | Hard | NQueensII.java | Backtrack + Memo |
77 | Combinations | Medium | Combinations.java | Backtrack |
78 | Subsets | Medium | Subset.java | Backtrack |
79 | Word Search | Medium | WordSearch.java | Backtrack |
90 | Subsets II | Medium | SubsetII.java | Backtrack |
93 | Restore IP Addresses | Medium | RestoreIPAddresses.java | Backtrack |
95 | Unique Binary Search Trees II | Medium | UniqueBinarySearchTreesII.java | Backtrack |
113 | Path Sum II | Medium | PathSumII.java | Backtrack |
216 | Combination Sum III | Medium | CombinationSumIII.java | Backtrack |
Search Path
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
329 | Longest Increasing Path in a Matrix | Hard | LongestIncreasingPathInAMatrix.java | DFS + Memo |
547 | Number of Provinces | Medium | NumberOfProvinces.java | DFS |
802 | Find Eventual Safe States | Hard | LongestIncreasingPathInAMatrix.java | DFS + Memo |
2267 | Check if There Is a Valid Parentheses String Path | Medium | FindEventualSafeStates.java | DFS |
Island
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
200 | Number of Islands | Medium | NumberOfIslands.java | DFS | Remove the island and count |
1254 | Number of Closed Islands | Medium | NumberOfClosedIslands.java | DFS | Remove the island close to the border, then Remove other islands and count. |
695 | Max Area of Island | Medium | MaxAreaOfIsland.java | DFS | Remove the island and count the area of each island. Return the max value. |
694 | Number of Distinct Islands | Medium | NumberOfDistinctIslands.java | DFS | remove the island and record the path, which could reflect the shape of the island, use HashSet to save the distinct path. |
1905 | Count Sub Islands | Medium | CountSubIslands.java | DFS | At first, remove the island that is not sub island. Then, remove the island and count. |
1020 | Number of Enclaves | Medium | NumberOfEnclaves.java | DFS | Remove the island close to the border, then Remove other islands and count. Same as problem '1254'. |
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
752 | Open the Lock | Medium | OpenTheLock.java | BFS with Queue |
752 | Network Delay Time | Medium | NetworkDelayTime.java | directed graph BFS | DFS |
286 | Walls and Gates | Medium | WallAndGates.java | BFS: spread from the gate |
994 | Rotting Oranges | Medium | RottingOranges.java | BFS: spread from the rotten oranges |
1091 | Shortest Path in Binary Matrix | Medium | ShortestPathInBinaryMatrix.java | BFS: spread from (0,0). The path that arrived earliest is the shortest. |
1197 | Minimum Knight Moves | Medium | MinimumKnightMoves.java | BFS: spread from (0,0). The path that arrived earliest is the shortest. |
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
31 | Next Permutation | Medium | NextPermutation.java | Find the first element that is greater than the previous element, then replace it with the greater and smallest element on the right side. |
228 | Summary Ranges | Easy | SummaryRanges.java | Two Pointer. |
281 | Zigzag Iterator | Medium | ZigzagIterator.java | Two Pointer Muti Pointer or Queue for the Follow-Up Question. |
386 | Lexicographical Numbers | Medium | LexicographicalNumbers.java | Recursion |
412 | Fizz Buzz | Easy | FizzBuzz.java | For loop. Calculate i%5 and i%3 separately. |
456 | 132 Pattern | Medium | OneThreeTwoPattern.java | Using Array as a Stack |
495 | Teemo Attacking | Easy | TeemoAttacking.java | Simulation |
605 | Can Place Flowers | Easy | CanPlaceFlowers.java | One Pass and Check |
768 | Max Chunks To Make Sorted II | Hard | MaxChunksToMakeSortedII.java | Iterate through the array, each time all elements to the left are smaller (or equal) to all elements to the right, there is a new chunk. |
769 | Max Chunks To Make Sorted | Medium | MaxChunksToMakeSorted.java | Iterate through the array, each time the maximum value of all elements to the left equals the index, there is a new chunk. |
953 | Verifying an Alien Dictionary | Easy | VerifyingAnAlienDictionary.java | Compare adjacent elements |
2239 | Find Closest Number to Zero | Easy | FindClosestNumberToZero.java | One Pass |
1480 | Running Sum of 1d Array | Easy | RunningSumOf1dArray.java | Prefix sum |
2284 | Sender With Largest Word Count | Medium | SenderWithLargestWordCount.java | Priority Queue |
2303 | Calculate Amount Paid in Taxes | Easy | CalculateAmountPaidInTaxes.java | One Pass |
x | Rearrange Sorted Array In MaxMin Form | Medium | RearrangeSortedArrayInMaxMinForm.java | Using % and / |
Two Pointer
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
88 | Merge Sorted Array | Easy | MergeSortedArray.java | Two Pointer |
581 | Shortest Unsorted Continuous Subarray | Medium | ShortestUnsortedContinuousSubarray.java | Two Pointer | Sort |
905 | Sort Array By Parity | Easy | SortArrayByParity.java | Two Pointer |
1679 | Max Number of K-Sum Pairs | Medium | MaxNumberOfKSumPairs.java | Two Pointer |
1695 | Maximum Erasure Value | Medium | MaximumErasureValue.java | Two Pointer | Prefix Sum |
Intervals
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
56 | Merge Intervals | Medium | MergeIntervals.java | Sort and compare left border of the interval |
57 | Insert Interval | Medium | InsertInterval.java | Add Before, Merge, Add After. |
986 | Interval List Intersections | Medium | IntervalListIntersections.java | Two pointer and Check intersect |
1272 | Remove Interval | Medium | RemoveInterval.java | Check Intersection |
1288 | Remove Covered Intervals | Medium | RemoveCoveredIntervals.java | Sort and compare the right border of the interval |
n Sum
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
167 | Two Sum II - Input Array Is Sorted | Medium | TwoSumIIInputArrayIsSorted.java | Two Pointer. |
voting
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
169 | Majority Element | Easy | MajorityElement.java | Sort | Boyer-Moore Voting Algorithm |
229 | Majority Element II | Medium | MajorityElementII.java | Sort | Boyer-Moore Voting Algorithm |
1150 | Check If a Number Is Majority Element in a Sorted Array | Easy | CheckIfANumberIsMajorityElementInASortedArray.java | Voting |
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
54 | Spiral Matrix | Medium | SpiralMatrix.java | 4 Bound |
59 | Spiral Matrix II | Medium | SpiralMatrixII.java | 4 Bound |
867 | Transpose Matrix | Easy | TransposeMatrix.java | Traversal |
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
374 | Guess Number Higher or Lower | Easy | GuessNumberHigherOrLower.java | Binary Search |
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
5 | Longest Palindromic Substring | Medium | LongestPalindromicSubstring.java | Two Pointer, Expand Around Possible Centers |
205 | Isomorphic Strings | Easy | IsomorphicStrings.java | Use HashMap and HashSet. |
535 | Encode and Decode TinyURL | Medium | EncodeAndDecodeTinyURL.java | HashMap |
647 | Palindromic Substrings | Medium | PalindromicSubstrings.java | Two Pointer, Expand Around Possible Centers |
844 | Backspace String Compare | Medium | BackspaceStringCompare.java | Stack | Two Pointer |
1209 | Remove All Adjacent Duplicates in String II | Medium | RemoveAllAdjacentDuplicatesInStringII.java | Stack | Two Pointer |
2027 | Minimum Moves to Convert String | Easy | MinimumMovesToConvertString.java | Pointer and Count |
2264 | Largest 3-Same-Digit Number in String | Easy | LargestThreeSameDigitNumberInString.java | Two Pointer |
2288 | Apply Discount to Prices | Medium | ApplyDiscountToPrices.java | Split, Format, StringBuilder |
Two Pointer
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
1332 | Remove Palindromic Subsequences | Easy | RemovePalindromicSubsequences.java | Two Pointer, check if it is a Palindrome String. |
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
3 | Longest Substring Without Repeating Characters | Medium | LongestSubstringWithoutRepeatingCharacters.java | Slide Window and HashMap |
567 | Permutation in String | Medium | PermutationInString.java | Slide Window |
1423 | Maximum Points You Can Obtain from Cards | Medium | MaximumPointsYouCanObtainFromCards.java | Slide Window |
1658 | Minimum Operations to Reduce X to Zero | Medium | MinimumOperationsToReduceXToZero.java | Slide Window |
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
451 | Sort Characters By Frequency | Medium | SortCharactersByFrequency.java | Map and Sort. Or Bucket Sort. |
567 | Longest Consecutive Sequence | Medium | LongestConsecutiveSequence.java | Hash Table: using HashSet save the nums. |
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
261 | Graph Valid Tree | Medium | GraphValidTree.java | This question is actually to determine whether there is a cycle in the graph. - generate Adjacency List - DFS - BFS |
399 | Evaluate Division | Medium | EvaluateDivision.java | - generate Adjacency List - DFS - BFS |
841 | Keys and Rooms | Medium | KeysAndRooms.java | - DFS - BFS |
133 | Clone Graph | Medium | CloneGraph.java | - DFS |
277 | Find the Celebrity | Medium | FindTheCelebrity.java | - Logical Deduction |
310 | Minimum Height Trees | Medium | MinimumHeightTrees.java | - BFS: remove leaves |
1192 | Critical Connections in a Network | Hard | CriticalConnectionsInANetwork.java | - DFS: find cycle and remove the edge. |
2368 | Reachable Nodes With Restrictions | Medium | ReachableNodesWithRestrictions.java | - DFS. |
Bipartite Graph
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
785 | Is Graph Bipartite? | Medium | IsBipartite.java | - Paint with different color - DFS -BFS |
886 | Possible Bipartite | Medium | PossibleBipartition.java | - Paint with different color - DFS -BFS |
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
63 | Unique Paths II | Medium | UniquePathsII.java | DP |
120 | Triangle | Medium | Triangle.java | DP |
256 | Paint House | Medium | PaintHouse.java | DP |
300 | Longest Increasing Subsequence | Medium | LongestIncreasingSubsequence.java | DP Bottom-up |
322 | Coin Change | Medium | CoinChange.java | DP Bottom-up |
474 | Ones and Zeroes | Medium | OnesAndZeroes.java | DP |
2266 | Count Number of Texts | Medium | CountNumberOfTexts.java | DP |
2369 | Check if There is a Valid Partition For The Array | Medium | CheckIfThereIsAValidPartitionForTheArray.java | DP |
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
347 | Top K Frequent Elements | Medium | TopKFrequentElements.java | Priority Queue |
692 | Top K Frequent Words | Medium | TopKFrequentWords.java | Priority Queue |
778 | Swim in Rising Water | Hard | SwimInRisingWater.java | Priority Queue |
1642 | Furthest Building You Can Reach | Medium | FurthestBuildingYouCanReach.java | Priority Queue |
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
32 | Longest Valid Parentheses | Hard | LongestValidParentheses.java | Stack |
316 | Remove Duplicate Letters | Medium | RemoveDuplicateLetters.java | Stack |
394 | Decode String | Medium | DecodeString.java | Two Stack |
921 | Minimum Add to Make Parentheses Valid | Medium | MinimumAddToMakeParenthesesValid.java | Balance |
1047 | Remove All Adjacent Duplicates In String | Easy | RemoveAllAdjacentDuplicatesInString.java | Use Stack or StringBuilder. |
1249 | Minimum Remove to Make Valid Parentheses | Medium | MinimumRemoveToMakeValidParentheses.java | Using Stack to save '(' |
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
171 | Excel Sheet Column Number | Easy | ExcelSheetColumnNumber.java | Iteration |
191 | Number of 1 Bits | Easy | LongestValidParentheses.java | n & (n - 1) |
202 | Happy Number | Easy | HappyNumber.java | HashSet | fast-slow pointer |
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
134 | Gas Station | Medium | GasStation.java | Greedy |
135 | Candy | Hard | Candy.java | From left to right, then form right to left. |
179 | Largest Number | Medium | LargestNumber.java | Greedy and Sort |
376 | Wiggle Subsequence | Medium | WiggleSubsequence.java | detect the change. |
1647 | Minimum Deletions to Make Character Frequencies Unique | Medium | MinimumDeletionsToMakeCharacterFrequenciesUnique.java | Greedy | HashSet | Sort |
1710 | Maximum Units on a Truck | Easy | MaximumUnitsOnATruck.java | select Greatest first. |
No. | Title | Difficulty | Solution | Idea |
---|---|---|---|---|
1268 | Search Suggestions System | Medium | SearchSuggestionsSystem.java | Trie | Binary Search |