zhaoguanchen/leetcode

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

LicenseBuild StatusLanguageLanguageLanguage

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.TitleShort Description
1TreeNodeDefinition for the Binary Tree node.
- construct List by Integer Array.
- print the Binary Tree with level order.
2ListNodeDefinition for the LinkedList node.
- construct List by Integer Array.
- construct by value.
- set cycle(to solve the cycle problems).
- print the LinkedList.
3NodeDefinition for the Tree node with next right pointers.
- construct List by Integer Array.
4NNodeDefinition for the N-ary Tree node.
- construct List by Integer Array.
- construct by value.

Tool class for handling issues such as format conversions.

No.TitleShort Description
1InputUtils.javaHandle Input Data Format
-java int[][] generateGrid(int m, int n, String s): convert String like "[[0,1],[0,2]]" to grid.

Reverse

No.TitleDifficultySolutionIdea
92Reverse Linked List IIMediumReverseLinkedListII.javaIteration | Recursion
Reverse Linked List between a and b. At first, we can move to a-th, and the problem becomes Reverse Top N nodes.
25Reverse Nodes in k-GroupHardReverseNodesInkGroup.javaFor each k group, reverse Linked List between head and k-th. Let head equal k+1th node, then do Recursion.
234Palindrome Linked ListEasyPalindromeLinkedList.java1. 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
143Reorder ListEasyReorderList.javaReverse the second-half List and Merge
147Insertion Sort ListEasyInsertionSortList.javaVirtual Head Node
206Reverse Linked ListEasyReverseLinkedList.javaIteration | Recursion
2130Maximum Twin Sum of a Linked ListMediumMaximumTwinSumOfALinkedList.javaReverse the second-half List

Two Pointer

No.TitleDifficultySolutionIdea
160Intersection of Two Linked ListsEasyIntersectionOfTwoLinkedLists.javaHash | A + B
No.TitleDifficultySolutionIdea
341Flatten Nested List IteratorMediumFlattenNestedListIterator.javaLinkedList, Deque, or Stack.
348Design Tic-Tac-ToeMediumDesignTicTacToe.javausing Array.
380Insert Delete GetRandom O(1)MediumInsertDeleteGetRandom.javaHashMap + ArrayList
622Design Circular QueueMediumDesignCircularQueue.javaUsing Array and Pointer.
705Design HashSetEasyDesignHashSet.javaArray + LinkedList
706Design HashMapEasyDesignHashMap.javaArray + LinkedList
1166Design File SystemMediumDesignFileSystem.java- 1. Trie: using HashMap as the child list.
1396Design Underground SystemMediumDesignUndergroundSystem.javausing two HashMap. One saves the check-in record, another saves the data of the current stage.
2102Sequentially Ordinal Rank TrackerHardSequentiallyOrdinalRankTracker.javaTwo Heap.

Traversal

No.TitleDifficultySolutionIdea
94Binary Tree Inorder TraversalEasyBinaryTreeInorderTraversal.javaRecursion and Iteration
144Binary Tree Preorder TraversalEasyBinaryTreePreorderTraversal.javaRecursion and Iteration
145Binary Tree Postorder TraversalEasyBinaryTreePostorderTraversal.javaRecursion and Iteration
314Binary Tree Vertical Order TraversalMediumBinaryTreeVerticalOrderTraversal.javaRecursion and Iteration
102Binary Tree Level Order TraversalMediumBinaryTreeLevelOrderTraversal.javaBFS

Construct

No.TitleDifficultySolutionIdea

Serialize and Deserialize

No.TitleDifficultySolutionIdea
No.TitleDifficultySolutionIdea
108Convert Sorted Array to Binary Search TreeMediumConvertSortedArrayToBinarySearchTree.javaDFS
129Sum Root to Leaf NumbersMediumSumRootOoLeafNumbers.javaDFS
199Binary Tree Right Side ViewMediumBinaryTreeRightSideView.javaDFS
366Find Leaves of Binary TreeMediumFindLeavesOfBinaryTree.javaPostorder traversal
404Sum of Left LeavesEasySumOfLeftLeaves.javaDFS
513Find Bottom Left Tree ValueMediumFindBottomLeftTreeValue.javaDFS
515Find Largest Value in Each Tree RowMediumFindLargestValueInEachTreeRow.javaBFS |DFS
617Merge Two Binary TreesEasyMergeTwoBinaryTrees.javaDFS
662Maximum Width of Binary TreeMediumMaximumWidthOfBinaryTree.javaBFS |DFS + The relationship of the index between the father node and the child node.
979Distribute Coins in Binary TreeMediumDistributeCoinsInBinaryTree.javaDFS
1302Deepest Leaves SumMediumDeepestLeavesSum.javaBFS | DFS
1379Find a Corresponding Node of a Binary Tree in a Clone of That TreeMediumFindACorrespondingNodeOfABinaryTreeInACloneOfThatTree.javainorder traversal
2265Count Nodes Equal to Average of SubtreeMediumCountNodesEqualToAverageOfSubtree.javaPostorder traversal
No.TitleDifficultySolutionIdea
173Binary Search Tree IteratorMediumBinarySearchTreeIterator.java
230Kth Smallest Element in a BSTMediumKthSmallestElementInABST.javaPreorder traversal
No.TitleDifficultySolutionIdea
222Count Complete Tree NodesMediumCountCompleteTreeNodes.javaConsider left and right separatly
No.TitleDifficultySolutionIdea
17Letter Combinations of a Phone NumberMediumLetterCombinationsPhoneNumber.javaBacktrack
39Combination SumMediumCombinationSum.javaBacktrack
40Combination Sum IIMediumCombinationSumII.javaBacktrack
46PermutationsMediumPermutations.javaBacktrack
47Permutations IIMediumPermutationsII.javaBacktrack
51N-QueensHardNQueens.javaBacktrack + Memo
52N-Queens IIHardNQueensII.javaBacktrack + Memo
77CombinationsMediumCombinations.javaBacktrack
78SubsetsMediumSubset.javaBacktrack
79Word SearchMediumWordSearch.javaBacktrack
90Subsets IIMediumSubsetII.javaBacktrack
93Restore IP AddressesMediumRestoreIPAddresses.javaBacktrack
95Unique Binary Search Trees IIMediumUniqueBinarySearchTreesII.javaBacktrack
113Path Sum IIMediumPathSumII.javaBacktrack
216Combination Sum IIIMediumCombinationSumIII.javaBacktrack

Search Path

No.TitleDifficultySolutionIdea
329Longest Increasing Path in a MatrixHardLongestIncreasingPathInAMatrix.javaDFS + Memo
547Number of ProvincesMediumNumberOfProvinces.javaDFS
802Find Eventual Safe StatesHardLongestIncreasingPathInAMatrix.javaDFS + Memo
2267Check if There Is a Valid Parentheses String PathMediumFindEventualSafeStates.javaDFS

Island

No.TitleDifficultySolutionIdea
200Number of IslandsMediumNumberOfIslands.javaDFS | Remove the island and count
1254Number of Closed IslandsMediumNumberOfClosedIslands.javaDFS | Remove the island close to the border, then Remove other islands and count.
695Max Area of IslandMediumMaxAreaOfIsland.javaDFS | Remove the island and count the area of each island. Return the max value.
694Number of Distinct IslandsMediumNumberOfDistinctIslands.javaDFS | remove the island and record the path, which could reflect the shape of the island, use HashSet to save the distinct path.
1905Count Sub IslandsMediumCountSubIslands.javaDFS | At first, remove the island that is not sub island. Then, remove the island and count.
1020Number of EnclavesMediumNumberOfEnclaves.javaDFS | Remove the island close to the border, then Remove other islands and count. Same as problem '1254'.
No.TitleDifficultySolutionIdea
752Open the LockMediumOpenTheLock.javaBFS with Queue
752Network Delay TimeMediumNetworkDelayTime.javadirected graph
BFS | DFS
286Walls and GatesMediumWallAndGates.javaBFS: spread from the gate
994Rotting OrangesMediumRottingOranges.javaBFS: spread from the rotten oranges
1091Shortest Path in Binary MatrixMediumShortestPathInBinaryMatrix.javaBFS: spread from (0,0). The path that arrived earliest is the shortest.
1197Minimum Knight MovesMediumMinimumKnightMoves.javaBFS: spread from (0,0). The path that arrived earliest is the shortest.
No.TitleDifficultySolutionIdea
31Next PermutationMediumNextPermutation.javaFind the first element that is greater than the previous element, then replace it with the greater and smallest element on the right side.
228Summary RangesEasySummaryRanges.javaTwo Pointer.
281Zigzag IteratorMediumZigzagIterator.javaTwo Pointer
Muti Pointer or Queue for the Follow-Up Question.
386Lexicographical NumbersMediumLexicographicalNumbers.javaRecursion
412Fizz BuzzEasyFizzBuzz.javaFor loop. Calculate i%5 and i%3 separately.
456132 PatternMediumOneThreeTwoPattern.javaUsing Array as a Stack
495Teemo AttackingEasyTeemoAttacking.javaSimulation
605Can Place FlowersEasyCanPlaceFlowers.javaOne Pass and Check
768Max Chunks To Make Sorted IIHardMaxChunksToMakeSortedII.javaIterate 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.
769Max Chunks To Make SortedMediumMaxChunksToMakeSorted.javaIterate through the array, each time the maximum value of all elements to the left equals the index, there is a new chunk.
953Verifying an Alien DictionaryEasyVerifyingAnAlienDictionary.javaCompare adjacent elements
2239Find Closest Number to ZeroEasyFindClosestNumberToZero.javaOne Pass
1480Running Sum of 1d ArrayEasyRunningSumOf1dArray.javaPrefix sum
2284Sender With Largest Word CountMediumSenderWithLargestWordCount.javaPriority Queue
2303Calculate Amount Paid in TaxesEasyCalculateAmountPaidInTaxes.javaOne Pass
xRearrange Sorted Array In MaxMin FormMediumRearrangeSortedArrayInMaxMinForm.javaUsing % and /

Two Pointer

No.TitleDifficultySolutionIdea
88Merge Sorted ArrayEasyMergeSortedArray.javaTwo Pointer
581Shortest Unsorted Continuous SubarrayMediumShortestUnsortedContinuousSubarray.javaTwo Pointer | Sort
905Sort Array By ParityEasySortArrayByParity.javaTwo Pointer
1679Max Number of K-Sum PairsMediumMaxNumberOfKSumPairs.javaTwo Pointer
1695Maximum Erasure ValueMediumMaximumErasureValue.javaTwo Pointer | Prefix Sum

Intervals

No.TitleDifficultySolutionIdea
56Merge IntervalsMediumMergeIntervals.javaSort and compare left border of the interval
57Insert IntervalMediumInsertInterval.javaAdd Before, Merge, Add After.
986Interval List IntersectionsMediumIntervalListIntersections.javaTwo pointer and Check intersect
1272Remove IntervalMediumRemoveInterval.javaCheck Intersection
1288Remove Covered IntervalsMediumRemoveCoveredIntervals.javaSort and compare the right border of the interval

n Sum

No.TitleDifficultySolutionIdea
167Two Sum II - Input Array Is SortedMediumTwoSumIIInputArrayIsSorted.javaTwo Pointer.

voting

No.TitleDifficultySolutionIdea
169Majority ElementEasyMajorityElement.javaSort | Boyer-Moore Voting Algorithm
229Majority Element IIMediumMajorityElementII.javaSort | Boyer-Moore Voting Algorithm
1150Check If a Number Is Majority Element in a Sorted ArrayEasyCheckIfANumberIsMajorityElementInASortedArray.javaVoting
No.TitleDifficultySolutionIdea
54Spiral MatrixMediumSpiralMatrix.java4 Bound
59Spiral Matrix IIMediumSpiralMatrixII.java4 Bound
867Transpose MatrixEasyTransposeMatrix.javaTraversal
No.TitleDifficultySolutionIdea
374Guess Number Higher or LowerEasyGuessNumberHigherOrLower.javaBinary Search
No.TitleDifficultySolutionIdea
5Longest Palindromic SubstringMediumLongestPalindromicSubstring.javaTwo Pointer, Expand Around Possible Centers
205Isomorphic StringsEasyIsomorphicStrings.javaUse HashMap and HashSet.
535Encode and Decode TinyURLMediumEncodeAndDecodeTinyURL.javaHashMap
647Palindromic SubstringsMediumPalindromicSubstrings.javaTwo Pointer, Expand Around Possible Centers
844Backspace String CompareMediumBackspaceStringCompare.javaStack | Two Pointer
1209Remove All Adjacent Duplicates in String IIMediumRemoveAllAdjacentDuplicatesInStringII.javaStack | Two Pointer
2027Minimum Moves to Convert StringEasyMinimumMovesToConvertString.javaPointer and Count
2264Largest 3-Same-Digit Number in StringEasyLargestThreeSameDigitNumberInString.javaTwo Pointer
2288Apply Discount to PricesMediumApplyDiscountToPrices.javaSplit, Format, StringBuilder

Two Pointer

No.TitleDifficultySolutionIdea
1332Remove Palindromic SubsequencesEasyRemovePalindromicSubsequences.javaTwo Pointer, check if it is a Palindrome String.
No.TitleDifficultySolutionIdea
3Longest Substring Without Repeating CharactersMediumLongestSubstringWithoutRepeatingCharacters.javaSlide Window and HashMap
567Permutation in StringMediumPermutationInString.javaSlide Window
1423Maximum Points You Can Obtain from CardsMediumMaximumPointsYouCanObtainFromCards.javaSlide Window
1658Minimum Operations to Reduce X to ZeroMediumMinimumOperationsToReduceXToZero.javaSlide Window
No.TitleDifficultySolutionIdea
451Sort Characters By FrequencyMediumSortCharactersByFrequency.javaMap and Sort. Or Bucket Sort.
567Longest Consecutive SequenceMediumLongestConsecutiveSequence.javaHash Table: using HashSet save the nums.
No.TitleDifficultySolutionIdea
261Graph Valid TreeMediumGraphValidTree.javaThis question is actually to determine whether there is a cycle in the graph.
- generate Adjacency List
- DFS
- BFS
399Evaluate DivisionMediumEvaluateDivision.java- generate Adjacency List
- DFS
- BFS
841Keys and RoomsMediumKeysAndRooms.java- DFS
- BFS
133Clone GraphMediumCloneGraph.java- DFS
277Find the CelebrityMediumFindTheCelebrity.java- Logical Deduction
310Minimum Height TreesMediumMinimumHeightTrees.java- BFS: remove leaves
1192Critical Connections in a NetworkHardCriticalConnectionsInANetwork.java- DFS: find cycle and remove the edge.
2368Reachable Nodes With RestrictionsMediumReachableNodesWithRestrictions.java- DFS.

Bipartite Graph

No.TitleDifficultySolutionIdea
785Is Graph Bipartite?MediumIsBipartite.java- Paint with different color
- DFS
-BFS
886Possible BipartiteMediumPossibleBipartition.java- Paint with different color
- DFS
-BFS
No.TitleDifficultySolutionIdea
63Unique Paths IIMediumUniquePathsII.javaDP
120TriangleMediumTriangle.javaDP
256Paint HouseMediumPaintHouse.javaDP
300Longest Increasing SubsequenceMediumLongestIncreasingSubsequence.javaDP Bottom-up
322Coin ChangeMediumCoinChange.javaDP Bottom-up
474Ones and ZeroesMediumOnesAndZeroes.javaDP
2266Count Number of TextsMediumCountNumberOfTexts.javaDP
2369Check if There is a Valid Partition For The ArrayMediumCheckIfThereIsAValidPartitionForTheArray.javaDP
No.TitleDifficultySolutionIdea
347Top K Frequent ElementsMediumTopKFrequentElements.javaPriority Queue
692Top K Frequent WordsMediumTopKFrequentWords.javaPriority Queue
778Swim in Rising WaterHardSwimInRisingWater.javaPriority Queue
1642Furthest Building You Can ReachMediumFurthestBuildingYouCanReach.javaPriority Queue
No.TitleDifficultySolutionIdea
32Longest Valid ParenthesesHardLongestValidParentheses.javaStack
316Remove Duplicate LettersMediumRemoveDuplicateLetters.javaStack
394Decode StringMediumDecodeString.javaTwo Stack
921Minimum Add to Make Parentheses ValidMediumMinimumAddToMakeParenthesesValid.javaBalance
1047Remove All Adjacent Duplicates In StringEasyRemoveAllAdjacentDuplicatesInString.javaUse Stack or StringBuilder.
1249Minimum Remove to Make Valid ParenthesesMediumMinimumRemoveToMakeValidParentheses.javaUsing Stack to save '('
No.TitleDifficultySolutionIdea
171Excel Sheet Column NumberEasyExcelSheetColumnNumber.javaIteration
191Number of 1 BitsEasyLongestValidParentheses.javan & (n - 1)
202Happy NumberEasyHappyNumber.javaHashSet | fast-slow pointer
No.TitleDifficultySolutionIdea
134Gas StationMediumGasStation.javaGreedy
135CandyHardCandy.javaFrom left to right, then form right to left.
179Largest NumberMediumLargestNumber.javaGreedy and Sort
376Wiggle SubsequenceMediumWiggleSubsequence.javadetect the change.
1647Minimum Deletions to Make Character Frequencies UniqueMediumMinimumDeletionsToMakeCharacterFrequenciesUnique.javaGreedy | HashSet | Sort
1710Maximum Units on a TruckEasyMaximumUnitsOnATruck.javaselect Greatest first.
No.TitleDifficultySolutionIdea
1268Search Suggestions SystemMediumSearchSuggestionsSystem.javaTrie | Binary Search

About

How to practice leetcode problem with local IDE

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages