This post contains a list of LeetCode problems that I found interesting during my time practicing Data Structures and Algorithms (DSA) questions and learning competitive programming knowledge. I have been continuously practicing LeetCode questions since April 2022, this list summaried my personal experience in learning the competitive programming. I will keep updating this list, and it also serves as a useful memo for me to look back on some key knowledge related to each question.
The first version of this list is build on 12-26-2023. The date of this post shows the time of last update.
The content of this post is better to be viewed along with the
search
function in your browser (keyboard shortcutctrl+f
orf3
)!
Patterns and Experiences
- For questions that ask us to answer multiple queries for a fixed input and return the answer of all queries, monotonicity usually plays an important role in it. In other words, we should process the queries in certain order and keep a part of input information to make decisions on the fly.
- If a question asks for the minimum number of steps for applying some operations to reach a certain final state, we can usually apply the reversal thinking if the operations are all invertible. In order words, we think how can we start from final state to reach the original input state.
- If the answer to certain question is just an integer, and there is monotonicity respect to the answer, then we can probably binary search the answer and check the answer in linear time.
- When we are required to find the minimum of maximums OR the maximum of minimums, this is also an common case involves binary search the results.
- In some problem involves string or integer with binary bit representation, we need to find the next input string/integer satisfy certain given condition. Instead of going through the whole input list, we can also directly construct the candidates that satisfy the constraints and then check if it is inside the input. For example, 126. Word Ladder II.
- For questions like subset sum partition or coin changes, we need to be careful about the order of outter/inner loop variables when implement the iterative dynamic programming.
- The pre and post order traversal of tree along with the empty nodes can uniquely identify the tree structure, however this is not true for inorder traversal.
- Linked list reverse and two point method can be very useful when you want to perform some operations on linked list with constant space complexity.
- Add an additional dummy node in linked list realted problem can be useful.
Tricks
- During the binary search, if you shrink left/right, you should calculate mid towards left/right, In the case you need to calculate mid toward right, use
mid = (l+r+1) // 2
. - The ceil/floor of an integer division
x/y
can be rewrite in the following way:(x+y-1)//y
andx//y
. - Python
@cache
decorator make the implementation of top-down dynamic programming much easier. However, we need to be careful about input arguments, make sure there is no redundant argument and all of them is hash compatible. In addition, callfunc.clear_cache()
at the end to avoid memory limitation exceed error on LeetCode. - Trie can be useful for bit XOR related problems. For example, we can find a $y$ in Trie that maximize $y \oplus x$ (e.g. 2935. Maximum Strong Pair XOR II). In addition, we can count the number of elements satisfy $y \oplus x \le v$ (see 1803. Count Pairs With XOR in a Range).
- Scanline algorithm do not need full size array to be allocated, we can also use a dictionary for implementation.
List of Problems
LCP 24. 数字游戏
The trick of subtracting each element with its position, i.e.,nums[i] -= i
.3003. Maximize the Number of Partitions After Operations
2910. Minimum Number of Groups to Create a Valid Assignment
Sometime, you need to analysis the brute force time complexity carefully.3022. Minimize OR of Remaining Elements Using Operations
2897. Apply Operations on Array to Maximize Sum of Squares
A type of question, minimize some bit operation (e.g. or) result of whole array, after some given operations. We can construct the answer by consider the value of each bit, i.e., solve the question “can we set the current considering bit to zero without break given constraints”.645. Set Mismatch
An interesting math problem, try solve it in constant space, it is very similar to but the solution is quite different as LC287, because the element is replaced, not something extra added.2719. Count of Integers
Another classical exmaple of digit programming. The implementation for this problem is in c++. Have to be extra careful about argument in c++, for complex argument type, we usually pass through reference&
, otherwise it is copied each time, very time consuming. Also the modulo operation in c++ does not take negative number into consideration. We need to do(n2-n1+modv) % modv
instead of(n2-n1) % modv
in Python. The code for this problem also serves as an example of implementing top-down dynamic programming in c++ using two arrayvis
andmemo
. Also, my implementation in this problem introduce a way of handling boundary cases by definingallow_bound
for digit based DP problems.3008. Find Beautiful Indices in the Given Array II
Practice of KMP string matching to find ALL occurrence of a pattern in the given string, can also be solved by using rolling hash (have an extremely small chance of hash collision). In case of english letters, consider them as digits with base-26.3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K
Digit dynamic programming, or mathematical analysis with combinatorics to compute the cost give the middle point, and use binary search over the candidate range of results.466. Count The Repetitions
The optimal solution involves find the “cycle section” between two strings. However, this can be tricky to implement and it is not so straight forward to me. Instead, we can solve it through pre-computation and binary lifting, which has almost the same time complexity.1124. Longest Well-Performing Interval
Monotonic stack, not asking for shortest but for longest pattern, the iteration order matters.1799. Maximize Score After N Operations
State compression dynamic programming.1687. Delivering Boxes from Storage to Ports
2945. Find Maximum Non-decreasing Array Length
Dynamic programming and monotonic queue/stack for maintaining the best set of candidates in certain range.808. Soup Servings
A statistical probability question that has limit when input n is large enough, we can have if statement for these case.3012. Minimize Length of Array Using Operations
Analysis, logical thinking question.940. Distinct Subsequences II
Dynamic programming, the definition of states here are important, and there is no choice to be made at each step.1806. Minimum Number of Operations to Reinitialize a Permutation
Permutation related problem, a good practice of analysis and math.2435. Paths in Matrix Whose Sum Is Divisible by K
Dynamic programming, table compression, implicit flip to optimize over along smaller dimension through lambda function.947. Most Stones Removed with Same Row or Column
990. Satisfiability of Equality Equations
Typical union find.858. Mirror Reflection
An interesting math question.240. Search a 2D Matrix II
Sometime, the start point matters. in this case, among the four corners, start from off diagonal works.2851. String Transformation
Very hard question from MathWorks. Need KMP to find all rotated string in the original string (double trick again), find DP recursive formula and it is actually a set of state transitions. And finally implement the DP through fast matrix power.796. Rotate String
The idea of adding another copy of original string to find the rotated string is very helpful.2499. Minimum Total Cost to Make Arrays Unequal
Analysis, two array problem, good practice of non stereotypical questions.2430. Maximum Deletions on a String
Longest common substring, two different dynamic programmings together.2421. Number of Good Paths
Actually an union find problem, make use of monotonicity and gradually add more nodes into graph.2407. Longest Increasing Subsequence II
Segment tree and dynamic programming.2382. Maximum Segment Sum After Removals
Reversal thinking, guarantee the monotonicity (the segment sum can only increase).2376. Count Special Integers
2801. Count Stepping Numbers in Range
2999. Count the Number of Powerful Integers
Digit based dynamic programming. The DP state is quite depends on the relationship between digits. Specifically, if all of them are in dependent, we usually only have three state parametersi, bound, target
, the target here is usually in string format in order to be hashable. Otherwise, the current choice of digit is depend on previous choice, in this case, we might need extra two state parametersd, zero
where d is the previous digit and zero indicates whether all previous digits are zero.2354. Number of Excellent Pairs
Simplifying the bit operation conditions, reformat the condition makes things clear.2332. The Latest Time to Catch a Bus
An annoying simulation based question, too many corner cases, try if you can accept with only one try.1686. Stone Game VI
Looks like dynamic programming, but it is actually greedy with priority queue, after some mathematical analysis.787. Cheapest Flights Within K Stops
Weighted shortest distance, with limitation on maximum jumps. Can solve through SPFS or Dijkstra.382. Linked List Random Node
Reservoir sampling, in the case that we cannot directly access the element by index, and the size of list is actually changing.316. Remove Duplicate Letters
402. Remove K Digits
1673. Find the Most Competitive Subsequence
A very good practice of stack based question, also a hint that we need stack when we have to revert some of previous choices. Better to use deque to solve it when there is requirement on the final size (2nd, 3rd).199. Binary Tree Right Side View
Interesting tree based question, can be solved quite easily using the idea of greedy and depth.1383. Maximum Performance of a Team
Monotonicity, with priority queue.2846. Minimum Edge Weight Equilibrium Queries in a Tree
Tree based two point path problem. Binary lifting, LCA with binary lifting (instead of classical two point LCA)!!2096. Step-By-Step Directions From a Binary Tree Node to Another
A simpler two point path related problem, also involves find the (Least Common Ancestor) LCA.2463. Minimum Total Distance Traveled
Linear sum assignment optimization problem, minimum weight matching in bipartite graphs.2402. Meeting Rooms III
Magic of priority queues, as well as monotonicity.2400. Number of Ways to Reach a Position After Exactly k Steps
The beauty of math, specifically combinatorics and analysis of the sufficient conditions.2289. Steps to Make Array Non-decreasing
Dynamic programming with monotonic stack, DP happens at the time of popping as well as inserting!!1996. The Number of Weak Characters in the Game
Keep only the Pareto points, sorting then linear scan.1461. Check If a String Contains All Binary Codes of Size K
Rolling hash, fixed size sliding window hashing.1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
Monotonic queue, and sliding window.1354. Construct Target Array With Multiple Sums
2007. Find Original Array From Doubled Array
2337. Move Pieces to Obtain a String
Analyze form the boundary, minimum or maximum.1130. Minimum Cost Tree From Leaf Values
2375. Construct Smallest Number From DI String
Question with inappropriate constraints. A very tricky question! Analyze how element is being used by focusing on two elements.875. Koko Eating Bananas
Binary search the possible results and check the validity of middle point in the search range.856. Score of Parentheses
Parentheses expression is related to recursive!735. Asteroid Collision
A very interesting stack related question.546. Remove Boxes
The hardest DP question I have ever seen. The choice and state definition of this problem is quite enlightening.332. Reconstruct Itinerary
Eulerian graph, try connecting with post-order dfs (node focused where in this case we are edge focused), something like post-order edge visit.329. Longest Increasing Path in a Matrix
Matrix grid based DP.315. Count of Smaller Numbers After Self
493. Reverse Pairs
Application of Binary Indexed Tree (BIT), with input rank mapping.312. Burst Balloons
Matrix chain multiplication variant. A good practice of dynamic programming.287. Find the Duplicate Number
Slow, fast pointer for cycle detection.241. Different Ways to Add Parentheses
679. 24 Game
Backtrack.207. Course Schedule
210. Course Schedule II
topological sort.215. Kth Largest Element in an Array
Quick select, partition algorithm, or priority queue.214. Shortest Palindrome
KMP string matching, and trick of adding a reversed copy of original string, and then use kmp to find the longest palindrome starting from the beginning (also works for prefix/suffix related questions).212. Word Search II
Trie, and DP.128. Longest Consecutive Sequence
Sliding window, or union find.124. Binary Tree Maximum Path Sum
Tree DP problem. Path related, typically consider each node as begin/end or middle point of the path.76. Minimum Window Substring
2009. Minimum Number of Operations to Make Array Continuous
2302. Count Subarrays With Score Less Than K
2327. Number of People Aware of a Secret
Classical sliding window.53. Maximum Subarray
152. Maximum Product Subarray
Interesting problem, try solve it through dynamic programming.34. Find First and Last Position of Element in Sorted Array
153. Find Minimum in Rotated Sorted Array
852. Peak Index in a Mountain Array
Binary search lower/upper bound or related practice question.28. Find the Index of the First Occurrence in a String
KMP string matching problem.834. Sum of Distances in Tree
2538. Difference Between Maximum and Minimum Price Sum
Root-change problem, the result for one given root can easily be answered through bfs/dfs, but now we want the result when every node can be treated as root with same amount of time. This is message-passing alike question and can be solved use belief propagation or just 2 rounds of dfs if the graph is tree (in most cases it is).2338. Count the Number of Ideal Arrays
Combinatorics question, can be solved by stars and bars theory.1920. Build Array from Permutation
41. First Missing Positive
Use one cell to save multiple informations. The key here is the modulo operations with a large enough number not going to appear in the input or based on the size of input.2386. Find the K-Sum of an Array
Ordered arbitrary size subset enumeration, this is not like LC982, which is binary mask based. Specifically, define the two subsets of current setS
asS + next(max(S))
andS - max(S) + next(max(S))
, we can form an recursive tree that involves all subsets of given array. Here, $next(\cdot)$ means the immediate next element that is larger than the input in the array. The+/-
here means set union or difference. More information can be found here.982. Triples with Bitwise AND Equal To Zero
Binary subset enumeration.1851. Minimum Interval to Include Each Query
2940. Find Building Where Alice and Bob Can Meet
Make use of monotonicity in hard questions is a very useful trick. To be more specific, if we process the queries in certain order, we can keep a set of candidates easily by make use of monotonicity.11. Container With Most Water
Monotonicity questions also usually involves monotonic queue or monotonic stack.887. Super Egg Drop
A dynamic programming question that treats the output value as part of its state.1163. Last Substring in Lexicographical Order
I would like to award this question as the one of the hardest two pointer related questions. The correct way of moving two points needs to be carefully analyzed.1639. Number of Ways to Form a Target String Given a Dictionary
1187. Make Array Strictly Increasing
1340. Jump Game V
Good practices of dynamic programming problem, the definition of choice here are very important.587. Erect the Fence
A 2D convex hall problem, also reminds me something important about cross product between two vectors. The results vector is perpendicular to both input vectors and the length of the resultant vector is the size of parallelogram formed by the input vectors. Also the sign the of results indicate the direction of final vector and it can be used to determine whether rotation direction is clockwise between the two vectors.1157. Online Majority Element In Subarray
Show you the power of randomized algorithm.2836. Maximize Value of Function in a Ball Passing Game
Binary lifting (make use of the fact that any number can be represented as the sum of powers of two), the graph structure here are inward tree with cyclic base, so solving through topological sort and analysis are also possible.2132. Stamping the Grid
This question makes me realize the relation between prefix sum, first-order difference of an array, and scan line algorithms. To put it simple, we can construct the result of scan line algorithm that equals a given prefix sum array by taking first-order difference of that array. This problem requires the prefix sum, and first-order difference techniques to be conducted in the 2D dimension.1074. Number of Submatrices That Sum to Target
Prefix sum technique in 2D matrix.1727. Largest Submatrix With Rearrangements
85. Maximal Rectangle
Sub matrix related question. Involves an technique of converting 2D problem into multiple 1D problems, with the values in 1D array represents some information of the matrix. Solve LC85 also involves LC1793 as a sub problem.935. Knight Dialer
State transition based dynamic programming problem. Each step we have multiple fixed states, and each of them is computed as the linear combination of previous states results. For DP problem like this, we can express the full transition in matrix form and use fast matrix power to compute the results in only $O(\log n)$ time.1793. Maximum Score of a Good Subarray
2334. Subarray With Elements Greater Than Varying Threshold
84. Largest Rectangle in Histogram
1856. Maximum Subarray Min-Product
Practice of monotonic stack for finding the next smaller/greater element. The standard solution needs two passes of the array using monotonic stack. We can also solve this problem in one pass by doing the analysis and work at the time of popping.2902. Count of Sub-Multisets With Bounded Sum
The ultimate knapsack problem. Compared with standard knapsack problem where each item only appear ones, how would you efficiently evaluate the recursive dynamic programming formula when each item can appear multiple times? The trick here is to use evenly-spaced sliding window technique multiple times, keeping final time complexity is still linear to number of entries.1488. Avoid Flood in The City
An interesting problem for priority queue, good logical questions for thinking the condition of push and pop from the queue. Note that this question can be easily solved using ordered data structures likeSortedList
in python.2127. Maximum Employees to Be Invited to a Meeting
内向基环树 (A cycle with multiple inward tree connected to its vertex) related problem, a good practice of using iterative topological sort to remove the trees from base cycle.424. Longest Repeating Character Replacement
2831. Find the Longest Equal Subarray
An example of Type II sliding window questions. Compared to standard sliding window that we increase right boundary one at a time and shrink the left to make the window valid (in other words, the size of window keeps reducing or increasing during the process), type II sliding window never decrease the size of window, when the window of size s is valid, we try size of s+1. If it does not work, we move the whole window with size s+1 right one step at a time. This can be useful for questions that only ask for longest subarrays, not some score of valid subarrays.395. Longest Substring with At Least K Repeating Characters
Type III sliding window questions. You will need to add more constraint to the sliding window being considering (e.g., limiting the number of unique elements in the window) such that standard sliding window technique can be applied. Then we can enumerate all possible constraints to get the final solution. In the case of alphabet strings, the number of unique elements inside window is limited.1349. Maximum Students Taking Exam
State compression dynamic programming, binary masking subset enumeration, bit operations for checking overlaps. The first problem I see that treat the assignment of whole row/col as the state.1611. Minimum One Bit Operations to Make Integers Zero
Dynamic programming, with reversal thinking since two operations are invertible. Also the idea of starting from the boundary.1901. Find a Peak Element II
Analysis, logical, math proof related question, good practice of binary search and mathematical proof.2916. Subarrays Distinct Element Sum of Squares II
Dynamic programming, and lazy segment trees with range sum query and range addition update.