Blind 75#
The Blind 75 is a curated LeetCode list for interview prep. Each problem includes the statement, Python solution(s), and explanations in the same format as DSA Patterns.
Explore overlaps
Compare this sheet with others in the DSA Venn Explorer.
How to use
- Try on LeetCode first — attempt the problem before reading solutions.
- Check the pattern link (when shown) for additional approaches in DSA Patterns.
- Compare your solution with the reference code below.
Arrays & Hashing#
1. Contains Duplicate (Leetcode:217)#
Problem Statement
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
Example 1:
Input: nums = [1,2,3,1] Output: true
Constraints:
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
Code and Explanation
- Walk the array: For each
num, check whether it is already inseen. - Duplicate found: If yes, return
Trueimmediately. - Otherwise insert: Add
numto the set and continue. - Result: Return
Falseafter the loop. O(n) time, O(n) space. - Time complexity: O(n)
- Space complexity: O(n)
- Sort the array: Bring equal values next to each other.
- Compare neighbors: If any
nums[i] == nums[i-1], a duplicate exists. - No extra structure: Uses only the sorted array.
- Tradeoff: O(n log n) time, O(1) extra space if sorting in place.
- Time complexity: O(n log n)
- Space complexity: O(1)
2. Encode and Decode Strings (Leetcode:271)#
Problem Statement
Design an algorithm to encode a list of strings to a single string and decode it back to the original list. The encoded string should be able to decode back to the original list of strings.
Example 1:
Input: ["neet","code","love","you"] Output: ["neet","code","love","you"]
Constraints:
- 1 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] contains any possible characters out of 256 valid ASCII characters
Code and Explanation
- Encode each string as
len#content. - Decode reads length until '#', then slices that many chars.
- Handles any character including delimiters.
- Time complexity: O(n)
- Space complexity: O(1)
3. Group Anagrams (Leetcode:49)#
Problem Statement
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Constraints:
- 1 <= strs.length <= 10^4
- 0 <= strs[i].length <= 100
- strs[i] consists of lowercase English letters
Code and Explanation
- Key = sorted tuple of chars groups anagrams.
- Append word to bucket; return all buckets.
- O(n * k log k) for word length k.
- Time complexity: O(n × k log k)
- Space complexity: O(n × k)
4. Jump Game (Leetcode:55)#
Also in DSA Patterns
Jump Game — 10. Greedy Algorithm (may include extra approaches and complexity analysis).
Problem Statement
You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.
Return true if you can reach the last index, or false otherwise.
Example 1:
Input: nums = [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: nums = [3,2,1,0,4] Output: false Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
Constraints:
1 <= nums.length <= 1040 <= nums[i] <= 105
Code and Explanation
- Track farthest reach:
far= max index reachable so far. - Early fail: If
i > far, indexiis unreachable. - Update reach:
far = max(far, i + nums[i]). - Success: Reach last index. O(n) time, O(1) space.
- Time complexity: O(n)
- Space complexity: O(1)
- State:
dp[i]= can we reach indexi? - From each reachable i: Mark all
i+1 .. i+nums[i]reachable. - **Return
dp[n-1]. - Correct but slower: O(n²) worst case.
- Time complexity: O(n²)
- Space complexity: O(n)
5. Product of Array Except Self (Leetcode:238)#
Also in DSA Patterns
Product of Array Except Self — 00. Prefix Sum (may include extra approaches and complexity analysis).
Problem Statement
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operation.
Example 1:
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Example 2:
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
Constraints:
2 <= nums.length <= 10^5
-30 <= nums[i] <= 30
The input is generated such thatanswer[i]is guaranteed to fit in a 32-bit integer.
Follow up:
Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)
Code and Explanation
- Prefix pass: Fill
answer[i]with product of all elements left ofiusing runningprefix. - Suffix pass: Walk right to left, multiplying running
suffixintoanswer[i]. - No division: Only multiplication, satisfying the problem constraint.
- Time complexity: O(n)
- Space complexity: O(1)
6. Two Sum (Leetcode:1)#
Also in DSA Patterns
Two Sum — 01. Two Pointers (may include extra approaches and complexity analysis).
Problem Statement
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6 Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6 Output: [0,1]
Constraints:
2 <= nums.length <= 10^4-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9Only one valid answer exists.
Follow Up:
Can you come up with an algorithm that is less than
O(n^2)time complexity?
Code and Explanation
- Scan the array once: Loop through
numswith indexiand valuenum. - Look for the complement: Compute
target - num. If that value is already inseen, return[seen[complement], i]. - Store what you have seen: Otherwise record
seen[num] = iso a later element can pair with it. - Time complexity: O(n)
- Space complexity: O(n)
- Pair values with indices: Build
[(num, index), ...]so sorting does not lose original positions. - Sort by value: Sort pairs ascending so two pointers can search for the target sum.
- Move pointers inward: If sum is too small, move
leftright; if too large, moverightleft; if equal, return stored indices. - Tradeoff: Easy to visualize but sorting costs O(n log n) vs O(n) for the hash map.
- Time complexity: O(n log n)
- Space complexity: O(n)
7. Valid Anagram (Leetcode:242)#
Problem Statement
Given two strings s and t, return true if t is an anagram of s, and false otherwise. An anagram is a word formed by rearranging the letters of another.
Example 1:
Input: s = "anagram", t = "nagaram" Output: true
Constraints:
- 1 <= s.length, t.length <= 5 * 10^4
- s and t consist of lowercase English letters
Code and Explanation
- Count chars in s, decrement for t.
- Anagram iff all counts zero.
- O(n) time.
- Time complexity: O(n)
- Space complexity: O(1)
Backtracking#
8. Combination Sum (Leetcode:39)#
Also in DSA Patterns
Combination Sum — 12. Backtracking (may include extra approaches and complexity analysis).
Problem Statement
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Example 1:
Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]] Explanation: 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations.
Example 2:
Input: candidates = [2,3,5], target = 8 Output: [[2,2,2,2],[2,3,3],[3,5]]
Example 3:
Input: candidates = [2], target = 1 Output: []
Constraints:
1 <= candidates.length <= 302 <= candidates[i] <= 40- All elements of
candidatesare distinct.1 <= target <= 40
Code and Explanation
- Sort candidates: Helps prune and handle duplicates if needed.
- Choose / explore / undo: Add a candidate, recurse with reduced target, remove on backtrack.
- Accept when target hits zero: Append current combination to results.
- Avoid reuse: Recurse from same index
ito allow reusing same number. - Time complexity: O(2^target)
- Space complexity: O(target)
9. Letter Combinations of a Phone Number (Leetcode:17)#
Also in DSA Patterns
Letter Combinations of a Phone Number — 12. Backtracking (may include extra approaches and complexity analysis).
Problem Statement
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example 1:
Input: digits = "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input: digits = "" Output: []
Example 3:
Input: digits = "2" Output: ["a","b","c"]
Constraints:
0 <= digits.length <= 4digits[i]is a digit in the range['2', '9'].
Code and Explanation
- Build combinations digit by digit with backtracking.
- At each index, append one mapped character and recurse to the next digit.
- When the path length equals the input length, push it into the result list.
10. Permutations (Leetcode:46)#
Also in DSA Patterns
Permutations — 12. Backtracking (may include extra approaches and complexity analysis).
Problem Statement
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Example 1:
Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Example 2:
Input: nums = [0,1] Output: [[0,1],[1,0]]
Example 3:
Input: nums = [1] Output: [[1]]
Constraints:
1 <= nums.length <= 6-10 <= nums[i] <= 10- All the integers of
numsare unique.
Code and Explanation
- Use backtracking to build one permutation at a time.
- Pick each unused number, recurse on the remaining values, then undo the choice.
- When no numbers remain, append a copy of the current path to the answer.
11. Word Search (Leetcode:79)#
Also in DSA Patterns
Word Search — 12. Backtracking (may include extra approaches and complexity analysis).
Problem Statement
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" Output: true
Example 2:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" Output: true
Example 3:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" Output: false
Constraints:
m == board.lengthn = board[i].length1 <= m, n <= 61 <= word.length <= 15boardandwordconsists of only lowercase and uppercase English letters.
Follow up: Could you use search pruning to make your solution faster with a larger board?
Code and Explanation
- Try each cell as start for word[0].
- DFS with index: Match next char in 4 directions.
- Mark visited temporarily (e.g.
'#'), restore on backtrack. - Return true on full match.
- Time complexity: O(m × n × 4^L)
- Space complexity: O(L)
Binary Search#
12. Find Minimum in Rotated Sorted Array (Leetcode:153)#
Problem Statement
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. Given the rotated array nums of distinct integers, return the minimum element.
Example 1:
Input: nums = [3,4,5,1,2] Output: 1 Explanation: The original array was [1,2,3,4,5] rotated 3 times.
Constraints:
- n == nums.length
- 1 <= n <= 5000
- -5000 <= nums[i] <= 5000
- All integers of nums are unique
- nums is sorted and rotated between 1 and n times
Code and Explanation
- Binary search on rotated array: Compare
nums[mid]withnums[right]. - If
nums[mid] > nums[right]: Minimum is in(mid, right]→left = mid + 1. - Else: Minimum is in
[left, mid]→right = mid. - Stop when
left == right: That index is the minimum. O(log n) time. - Time complexity: O(log n)
- Space complexity: O(1)
13. Search in Rotated Sorted Array (Leetcode:33)#
Also in DSA Patterns
Search in Rotated Sorted Array — 09. Binary Search (may include extra approaches and complexity analysis).
Problem Statement
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is possibly left rotated at an unknown index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be left rotated by 3 indices and become [4,5,6,7,0,1,2].
Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1
Example 3:
Input: nums = [1], target = 0 Output: -1
Constraints:
1 <= nums.length <= 5000-104 <= nums[i] <= 104- All values of
numsare unique.numsis an ascending array that is possibly rotated.-104 <= target <= 104
Code and Explanation
- Binary search frame: Keep
leftandrighton the rotated sorted array. - Find sorted half: Compare
nums[left]withnums[mid]. - Locate target: Check if target lies in the sorted half's value range; shrink search there.
- Return index or -1: O(log n) time, O(1) space.
- Time complexity: O(log n)
- Space complexity: O(1)
Bit Manipulation#
14. Counting Bits (Leetcode:338)#
Also in DSA Patterns
Counting Bits — 06. Bit Manipulation (may include extra approaches and complexity analysis).
Problem Statement
Given an integer n, return an array ans of length n + 1 where ans[i] is the number of 1s in the binary representation of i.
Example 1:
Input: n = 2
Output: [0,1,1]
Example 2:
Input: n = 5
Output: [0,1,1,2,1,2]
Constraints:
0 <= n <= 10^5
Code and Explanation
- Base case:
dp[0] = 0. - Even i:
dp[i] = dp[i >> 1]— same bit count as i/2. - Odd i:
dp[i] = dp[i >> 1] + 1— one extra bit vs i/2. - Build table 0..n: O(n) time, O(n) space.
- Time complexity: O(n)
- Space complexity: O(n)
15. Missing Number (Leetcode:268)#
Also in DSA Patterns
Missing Number — 05. Cyclic Sort (may include extra approaches and complexity analysis).
Problem Statement
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
Example 1:
Input: nums = [3,0,1] Output: 2
Constraints:
n == nums.length,1 <= n <= 10^4,0 <= nums[i] <= n, all unique.
Code and Explanation
- Expected sum: Numbers 0..n sum to
n*(n+1)/2. - Actual sum: Add all elements in
nums. - Missing value: Difference between expected and actual.
- Time complexity: O(n)
- Space complexity: O(1)
- XOR all indices 0..n with all array values.
- Pairs cancel: Duplicate index/value pairs XOR to 0.
- Remaining value: The missing number.
- Time complexity: O(n)
- Space complexity: O(1)
16. Number of 1 Bits (Leetcode:191)#
Also in DSA Patterns
Number of 1 Bits — 06. Bit Manipulation (may include extra approaches and complexity analysis).
Problem Statement
Write a function that takes the binary representation of a positive integer and returns the number of set bits it has (also known as the Hamming weight).
Example 1:
Input: n = 11 Output: 3 Explanation: The input binary string 1011 has a total of three set bits.
Constraints:
- 2^31 <= n < 2^31
Code and Explanation
- Check least significant bit:
n & 1tells if the last bit is set. - Shift right:
n >>= 1processes the next bit. - Count set bits: Increment counter each time LSB is 1.
- Time complexity: O(1)
- Space complexity: O(1)
- Clear lowest set bit:
n &= n - 1drops the rightmost 1-bit. - Count iterations: Each loop removes one set bit.
- Stop at zero: Number of iterations equals Hamming weight.
- Faster when sparse: O(# of set bits) instead of O(32).
- Time complexity: O(k)
- Space complexity: O(1)
17. Reverse Bits (Leetcode:190)#
Also in DSA Patterns
Reverse Bits — 06. Bit Manipulation (may include extra approaches and complexity analysis).
Problem Statement
Reverse bits of a given 32 bits unsigned integer.
Example 1:
Input: n = 43261596 Output: 964176192 Explanation: The binary representation is reversed.
Constraints:
- The input must be a binary string of length 32
Code and Explanation
- Extract LSB:
n & 1appends to result. - Shift result left, n right: Repeat 32 times for 32-bit input.
- Build reversed bits: Result accumulates from LSB to MSB of original.
- Time complexity: O(1)
- Space complexity: O(1)
18. Sum of Two Integers (Leetcode:371)#
Also in DSA Patterns
Sum of Two Integers — 06. Bit Manipulation (may include extra approaches and complexity analysis).
Problem Statement
Given two integers a and b, return the sum of the two integers without using the operators + and -.
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = 2, b = 3
Output: 5
Constraints:
-1000 <= a, b <= 1000
Code and Explanation
- XOR gives sum without carry:
a ^ badds bits ignoring carry. - AND + shift finds carry:
(a & b) << 1is carry shifted left. - Repeat until carry is zero: Mask to 32-bit unsigned to simulate fixed-width arithmetic.
- Convert back to signed: Handle Python's unbounded integers. O(1) bit width.
- Time complexity: O(1)
- Space complexity: O(1)
Design#
19. Find Median from Data Stream (Leetcode:295)#
Also in DSA Patterns
Find Median from Data Stream — 15. Heaps (may include extra approaches and complexity analysis).
Problem Statement
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.
- For example, for
arr = [2,3,4], the median is3. - For example, for
arr = [2,3], the median is(2 + 3) / 2 = 2.5.
Implement the MedianFinder class:
MedianFinder()initializes theMedianFinderobject.void addNum(int num)adds the integernumfrom the data stream to the data structure.double findMedian()returns the median of all elements so far. Answers within10-5of the actual answer will be accepted.
Example 1:
Input ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"] [[], [1], [2], [], [3], []] Output [null, null, null, 1.5, null, 2.0]
Explanation MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr[1, 2, 3] medianFinder.findMedian(); // return 2.0
Constraints:
-105 <= num <= 105- There will be at least one element in the data structure before calling
findMedian.- At most
5 * 104calls will be made toaddNumandfindMedian.
Follow up:
- If all integer numbers from the stream are in the range
[0, 100], how would you optimize your solution?- If
99%of all integer numbers from the stream are in the range[0, 100], how would you optimize your solution?
Code and Explanation
- Max-heap
smallholds lower half; min-heaplargeholds upper half. - After each insert, rebalance so sizes differ by at most 1.
- Median is top of small (odd count) or average of both tops (even).
- Time complexity: O(log n) per add
- Space complexity: O(n)
20. Serialize and Deserialize Binary Tree (Leetcode:297)#
Also in DSA Patterns
Serialize and Deserialize Binary Tree — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
Example 1:
Input: root = [1,2,3,null,null,4,5] Output: [1,2,3,null,null,4,5]
Constraints:
- The number of nodes is in the range [0, 10^4]
- -1000 <= Node.val <= 1000
Code and Explanation
- Preorder with 'N' for null encodes structure + values.
- Deserialize reads tokens in same order recursively.
- Iterator ensures correct node sequence.
- Time complexity: O(n)
- Space complexity: O(n)
Dynamic Programming#
21. Best Time to Buy and Sell Stock (Leetcode:121)#
Also in DSA Patterns
Best Time to Buy and Sell Stock — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize profit by choosing a single day to buy and a different day in the future to sell. Return the maximum profit. If no profit is possible, return 0.
Example 1:
Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6 - 1 = 5.
Constraints:
- 1 <= prices.length <= 10^5
- 0 <= prices[i] <= 10^4
Code and Explanation
- Track cheapest buy price:
min_pricestores the lowest price seen while scanning left to right. - Profit if selling today: At each day,
price - min_priceis the best profit ending on that day. - Keep global maximum: Update
max_profitwhenever today's profit beats the record. - Why one pass works: The best sell day for any buy must come after that buy. O(n) time, O(1) space.
- Time complexity: O(n)
- Space complexity: O(1)
22. Climbing Stairs (Leetcode:70)#
Also in DSA Patterns
Climbing Stairs — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
You are climbing a staircase. It takes n steps to reach the top. Each time you can climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 3 Output: 3 Explanation: 1+1+1, 1+2, or 2+1.
Constraints:
- 1 <= n <= 45
Code and Explanation
- Base cases: 1 way to reach step 1; 2 ways to reach step 2.
- Fibonacci recurrence: Ways to step
i= ways(i-1) + ways(i-2). - Rolling variables: Only keep last two states in
aandb. - Time complexity: O(n)
- Space complexity: O(1)
- Recursive definition:
dp(i)= ways to reach stepi. - Base:
dp(1)=1,dp(2)=2. - Memoize: Store computed
dp(i)to avoid recomputation. - Tradeoff: Same logic as bottom-up; uses O(n) recursion stack.
- Time complexity: O(n)
- Space complexity: O(n)
23. Coin Change (Leetcode:322)#
Also in DSA Patterns
Coin Change II – Minimum Number of Coins — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins needed to make up that amount. If impossible, return -1.
Example 1:
Input: coins = [1,2,5], amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1.
Constraints:
- 1 <= coins.length <= 12
- 1 <= coins[i] <= 2^31 - 1
- 0 <= amount <= 10^4
Code and Explanation
- State:
dp[a]= minimum coins to make amounta. - Initialize:
dp[0]=0, others to infinity. - Transition: For each amount, try every coin:
dp[a] = min(dp[a], 1 + dp[a-coin]). - Answer:
dp[amount]or -1 if unreachable. O(amount * coins) time. - Time complexity: O(amount × coins)
- Space complexity: O(amount)
- Recursive function:
dp(remaining)= min coins for that amount. - Try each coin: Return
1 + min(dp(remaining - coin)). - Memo table: Cache results by remaining amount.
- Same complexity as bottom-up but top-down is often easier to write first.
- Time complexity: O(amount × coins)
- Space complexity: O(amount)
24. Combination Sum IV (Leetcode:377)#
Problem Statement
Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.
The test cases are generated so that the answer can fit in a 32-bit integer.
Example 1:
Input: nums = [1,2,3], target = 4 Output: 7 Explanation: The possible combination ways are: (1, 1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 3), (2, 1, 1), (2, 2), (3, 1)
Example 2:
Input: nums = [9], target = 3 Output: 0
Constraints:
1 <= nums.length <= 2001 <= nums[i] <= 1000- All the elements of
numsare unique.1 <= target <= 1000
Code and Explanation
- Use bottom-up dynamic programming where
dp[i]counts combinations summing toi. - Initialize
dp[0] = 1because one empty combination forms sum zero. - For each total, add combinations from every coin that can contribute to it.
25. Decode Ways (Leetcode:91)#
Also in DSA Patterns
Decode Ways — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
You have intercepted a secret message encoded as a string of numbers. The message is decoded via the following mapping:
"1" -> 'A'
"2" -> 'B'
...
"25" -> 'Y'
"26" -> 'Z'
However, while decoding the message, you realize that there are many different ways you can decode the message because some codes are contained in other codes ("2" and "5" vs "25").
For example, "11106" can be decoded into:
"AAJF"with the grouping(1, 1, 10, 6)"KJF"with the grouping(11, 10, 6)- The grouping
(1, 11, 06)is invalid because"06"is not a valid code (only"6"is valid).
Note: there may be strings that are impossible to decode.
Given a string s containing only digits, return the number of ways to decode it. If the entire string cannot be decoded in any valid way, return 0.
The test cases are generated so that the answer fits in a 32-bit integer.
Example 1:
Input: s = "12" Output: 2 Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: s = "226" Output: 3 Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
Example 3:
Input: s = "06" Output: 0 Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06"). In this case, the string is not a valid encoding, so return 0.
Constraints:
1 <= s.length <= 100scontains only digits and may contain leading zero(s).
Code and Explanation
- State:
dp[i]= ways to decode prefix of lengthi. - Single digit: Valid if
s[i-1]is not'0'. - Two digits: Valid if substring
s[i-2:i]is 10-26. - Sum transitions:
dp[i] = dp[i-1] + dp[i-2](when valid). - Time complexity: O(n)
- Space complexity: O(n)
26. House Robber (Leetcode:198)#
Also in DSA Patterns
House Robber I — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stored. Adjacent houses have security systems connected — you cannot rob two adjacent houses. Return the maximum amount you can rob without alerting the police.
Example 1:
Input: nums = [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and house 3 (money = 3), total = 4.
Constraints:
- 1 <= nums.length <= 100
- 0 <= nums[i] <= 400
Code and Explanation
- State:
dp[i]= max money from houses0..i. - Choice at house i: Rob it (
dp[i-2]+nums[i]) or skip (dp[i-1]). - Rolling variables: Only need previous two DP values.
- O(n) time, O(1) space.
- Time complexity: O(n)
- Space complexity: O(1)
27. House Robber II (Leetcode:213)#
Also in DSA Patterns
House Robber II — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
You are a professional robber planning to rob houses arranged in a circle, meaning the first and last houses are adjacent. Return the maximum amount you can rob without robbing two adjacent houses.
Example 1:
Input: nums = [2,3,2] Output: 3 Explanation: Rob house 2 (money = 3); cannot rob both 1 and 3.
Constraints:
- 1 <= nums.length <= 100
- 0 <= nums[i] <= 1000
Code and Explanation
- Two linear runs: Rob houses
0..n-2and1..n-1separately. - Why: First and last houses cannot both be robbed.
- Reuse house robber I logic on each segment.
- Answer: Max of the two runs.
- Time complexity: O(n)
- Space complexity: O(1)
28. Longest Common Subsequence (Leetcode:1143)#
Problem Statement
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
Example 1:
Input: text1 = "abcde", text2 = "ace" Output: 3 Explanation: The LCS is "ace".
Constraints:
- 1 <= text1.length, text2.length <= 1000
- text1 and text2 consist of only lowercase English characters
Code and Explanation
- Table:
dp[i][j]= LCS length oftext1[:i]andtext2[:j]. - Match: If chars equal,
dp[i][j] = dp[i-1][j-1] + 1. - Mismatch:
dp[i][j] = max(dp[i-1][j], dp[i][j-1]). - Answer:
dp[m][n]. O(mn) time and space. - Time complexity: O(m × n)
- Space complexity: O(m × n)
- Only need previous row: Keep
prevandcurrarrays of sizelen(text2)+1. - Same transitions as 2D DP but roll rows.
- Return last cell of final row.
- Space: O(min(m,n)) instead of O(mn).
- Time complexity: O(m × n)
- Space complexity: O(min(m, n))
29. Longest Increasing Subsequence (Leetcode:300)#
Also in DSA Patterns
Longest Increasing Subsequence — 09. Binary Search (may include extra approaches and complexity analysis).
Problem Statement
Given an integer array nums, return the length of the longest strictly increasing subsequence**.
Example 1:
Input: nums = [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Example 2:
Input: nums = [0,1,0,3,2,3] Output: 4
Example 3:
Input: nums = [7,7,7,7,7,7,7] Output: 1
Constraints:
1 <= nums.length <= 2500-104 <= nums[i] <= 104
Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?
Code and Explanation
- Tail array:
tails[i]= smallest tail of an increasing subsequence of lengthi+1. - Process each number: Binary search where
numfits intails; extend or replace. - Length of tails: Final LIS length equals
len(tails). - Optimal for LIS: O(n log n) time, O(n) space.
- Time complexity: O(n log n)
- Space complexity: O(n)
- State:
dp[i]= LIS length ending at indexi. - Transition: For each
j < iwithnums[j] < nums[i], setdp[i] = max(dp[i], dp[j]+1). - Answer:
max(dp). - Easier to code: O(n²) time — good for interviews before optimizing.
- Time complexity: O(n²)
- Space complexity: O(n)
30. Longest Palindromic Substring (Leetcode:5)#
Also in DSA Patterns
Longest Palindromic Substring — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
Given a string s, return the longest palindromic substring in s.
Example 1:
Input: s = "babad" Output: "bab" Explanation: "aba" is also a valid answer.
Constraints:
- 1 <= s.length <= 1000
- s consists of only digits and English letters
Code and Explanation
- Each index (and between indices) is a center.
- Expand while chars match.
- Track longest palindrome found.
- O(n²) time, O(1) space.
- Time complexity: O(n²)
- Space complexity: O(1)
- dp[i][j] true if s[i:j+1] palindrome.
- Fill by increasing length using inner substrings.
- Track best start/end.
- O(n²) time and space.
- Time complexity: O(n²)
- Space complexity: O(n²)
31. Maximum Product Subarray (Leetcode:152)#
Also in DSA Patterns
Maximum Product Subarray — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
Given an integer array nums, find a subarray that has the largest product, and return the product.
Example 1:
Input: nums = [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6.
Constraints:
- 1 <= nums.length <= 2 * 10^4
- -10 <= nums[i] <= 10
- The product of any subarray fits in a 32-bit integer
Code and Explanation
- Track max and min product ending here: Negatives can flip a small product into a large one.
- Update at each index: Compute new max/min from
num,num*max_here, andnum*min_here. - Record global best:
result = max(result, max_here). - Why: Zeros reset; negatives swap max/min roles. O(n) time, O(1) space.
- Time complexity: O(n)
- Space complexity: O(1)
32. Maximum Subarray (Leetcode:53)#
Also in DSA Patterns
Maximum Subarray — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
Given an integer array nums, find the subarray with the largest sum, and return its sum.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: The subarray [4,-1,2,1] has the largest sum 6.
Constraints:
- 1 <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
Code and Explanation
- Track two values:
current= best sum ending here;best= best sum anywhere. - Extend or restart: Add current number to
current, or restart from current number. - Update global best:
best = max(best, current)each step. - Intuition: Negative running sums should not carry forward. O(n) time, O(1) space.
- Time complexity: O(n)
- Space complexity: O(1)
- Split in half: Recursively solve left, right, and crossing subarray through
mid. - Crossing sum: Expand from
midoutward for best sum using both halves. - Combine: Answer is
max(left, right, crossing). - Tradeoff: Correct but O(n log n); Kadane's is preferred.
- Time complexity: O(n log n)
- Space complexity: O(log n)
33. Palindromic Substrings (Leetcode:647)#
Also in DSA Patterns
Count of Palindromic Substrings — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
Given a string s, return the number of palindromic substrings in it. A string is a palindrome when it reads the same backward as forward.
Example 1:
Input: s = "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c".
Constraints:
- 1 <= s.length <= 1000
- s consists of lowercase English letters
Code and Explanation
- Expand from each center; count valid palindromes.
- Odd and even centers handled separately.
- Time complexity: O(n²)
- Space complexity: O(1)
- dp[i][j] palindrome flag; count true entries.
- Fill i backwards so inner substrings ready.
- Time complexity: O(n²)
- Space complexity: O(n²)
34. Unique Paths (Leetcode:62)#
Also in DSA Patterns
Unique Paths in Grid — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
There is a robot on an m x n grid. The robot is initially at the top-left corner and tries to move to the bottom-right corner. The robot can only move down or right. How many unique paths are there?
Example 1:
Input: m = 3, n = 7 Output: 28
Constraints:
- 1 <= m, n <= 100
Code and Explanation
- Grid DP:
dp[r][c]= paths to cell(r,c). - Only from top or left:
dp[r][c] = dp[r-1][c] + dp[r][c-1]. - First row/column: Only one way along edges.
- Math alternative: C((m-1)+(n-1), m-1) also works.
- Time complexity: O(m × n)
- Space complexity: O(n)
35. Word Break (Leetcode:139)#
Problem Statement
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "leetcode", wordDict = ["leet","code"] Output: true Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple","pen"] Output: true Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] Output: false
Constraints:
1 <= s.length <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20sandwordDict[i]consist of only lowercase English letters.- All the strings of
wordDictare unique.
Code and Explanation
- State:
dp[i]= True ifs[:i]can be segmented. - Base:
dp[0] = True(empty prefix). - Transition: For each start
j, ifdp[j]ands[j:i]in dictionary, setdp[i]=True. - Answer:
dp[len(s)]. O(n² * dict lookup). - Time complexity: O(n² × m)
- Space complexity: O(n)
- Graph view: Edge from index
itojifs[i:j]is a valid word. - BFS from 0: Reach
len(s)means string is breakable. - Visited set: Skip reprocessing same start index.
- Same logical problem, different traversal style.
- Time complexity: O(n² × m)
- Space complexity: O(n)
Graphs#
36. Clone Graph (Leetcode:133)#
Problem Statement
Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Each node contains a value (int) and a list of its neighbors.
Example 1:
Input: adjList = [[2,4],[1,3],[2,4],[1,3]] Output: [[2,4],[1,3],[2,4],[1,3]]
Constraints:
- The number of nodes is in the range [0, 100]
- Node.val is unique for each node
- Node.val is generated as a small integer
- No repeated edges and no self-loops
- The graph is connected and all nodes can be visited from the given node
Code and Explanation
- Clone map:
clones[original]stores the copied node for each original. - DFS from start: If already cloned, return existing copy.
- Create copy and wire neighbors: Clone node, then DFS each neighbor and append clone to neighbor list.
- O(V+E) time and space.
- Time complexity: O(V + E)
- Space complexity: O(V)
- Queue traversal: Process nodes level by level while cloning.
- Clone on first visit: Add to map and queue when neighbor first seen.
- Wire neighbors: Append cloned neighbor pointers from map.
- Same complexity as DFS, iterative style.
- Time complexity: O(V + E)
- Space complexity: O(V)
37. Course Schedule (Leetcode:207)#
Problem Statement
There are a total of numCourses courses labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates you must take course bi before ai. Return true if you can finish all courses, or false if there is a cycle.
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]] Output: true Explanation: Take course 0 then course 1.
Constraints:
- 1 <= numCourses <= 2000
- 0 <= prerequisites.length <= 5000
- prerequisites[i].length == 2
- 0 <= ai, bi < numCourses
- All pairs are unique
Code and Explanation
- Build graph and indegree: Edge
prereq -> course. - Start with indegree 0 courses in a queue.
- Pop course, reduce indegree of neighbors: If indegree hits 0, enqueue.
- No cycle iff all courses processed. O(V+E).
- Time complexity: O(V + E)
- Space complexity: O(V + E)
- Adjacency list: Store prerequisites per course.
- Three states: unvisited, visiting, done.
- Back edge = cycle: Revisit a visiting node.
- All nodes finish without cycle → true.
- Time complexity: O(V + E)
- Space complexity: O(V + E)
38. Graph Valid Tree (Leetcode:261)#
Problem Statement
Given n nodes labeled from 0 to n - 1 and a list of undirected edges, write a function to check whether these edges make up a valid tree. A valid tree has no cycles and is fully connected.
Example 1:
Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]] Output: true
Constraints:
- 1 <= n <= 2000
- 0 <= edges.length <= 5000
- edges[i].length == 2
- 0 <= ai, bi < n
- ai != bi
- No duplicate edges
Code and Explanation
- Tree check: Valid tree with n nodes has exactly
n-1edges. - Union-Find merge: If two nodes already share a root, cycle exists.
- No cycle + n-1 edges ⇒ connected tree.
- Time complexity: O(n × α(n))
- Space complexity: O(n)
39. Number of Connected Components in an Undirected Graph (Leetcode:323)#
Problem Statement
You have a graph of n nodes labeled from 0 to n - 1. You are given an integer n and an array edges where edges[i] = [ai, bi] indicates an undirected edge between nodes ai and bi. Return the number of connected components.
Example 1:
Input: n = 5, edges = [[0,1],[1,2],[3,4]] Output: 2
Constraints:
- 1 <= n <= 2000
- 1 <= edges.length <= 5000
- edges[i].length == 2
- 0 <= ai, bi < n
- ai != bi
- No duplicate edges
Code and Explanation
- Start with n components.
- Union each edge: If nodes in different sets, merge and decrement count.
- Return final component count. O(n α(n)).
- Time complexity: O(n × α(n))
- Space complexity: O(n)
40. Number of Islands (Leetcode:200)#
Problem Statement
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] Output: 1
Example 2:
Input: grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ] Output: 3
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 300grid[i][j]is'0'or'1'.
Code and Explanation
- Scan grid: Each unvisited
'1'starts a new island. - DFS flood fill: Mark visited by flipping to
'0'. - Explore 4 directions recursively.
- Count DFS launches. O(mn) time.
- Time complexity: O(m × n)
- Space complexity: O(m × n)
- Same outer scan as DFS for new land cells.
- Queue flood fill: Process cells layer by layer.
- Mark visited on enqueue to avoid duplicates.
- Equivalent result, iterative traversal.
- Time complexity: O(m × n)
- Space complexity: O(m × n)
41. Pacific Atlantic Water Flow (Leetcode:417)#
Problem Statement
There is an m x n rectangular island bordered by the Pacific Ocean (top and left edges) and Atlantic Ocean (bottom and right edges). Rain water flows to adjacent cells with equal or lower height. Find the list of grid coordinates where water can flow to both oceans.
Example 1:
Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]] Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
Constraints:
- m == heights.length
- n == heights[r].length
- 1 <= m, n <= 200
- 0 <= heights[r][c] <= 10^5
Code and Explanation
- Reverse the flow: Start DFS from Pacific borders (top/left) and Atlantic borders (bottom/right).
- Climb uphill: Move to neighbor if height >= current.
- Two reachable sets: Cells in both sets drain to both oceans.
- Return intersection. O(mn) time.
- Time complexity: O(m × n)
- Space complexity: O(m × n)
Heap / Priority Queue#
42. Merge k Sorted Lists (Leetcode:23)#
Also in DSA Patterns
Merge k Sorted Lists — 07. Linked List (may include extra approaches and complexity analysis).
Problem Statement
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted linked list: 1->1->2->3->4->4->5->6
Example 2:
Input: lists = [] Output: []
Example 3:
Input: lists = [[]] Output: []
Constraints:
k == lists.length0 <= k <= 1040 <= lists[i].length <= 500-104 <= lists[i][j] <= 104lists[i]is sorted in ascending order.- The sum of
lists[i].lengthwill not exceed104.
Code and Explanation
- Push head of each list onto min-heap.
- Pop smallest, append to result, push that node's next.
- O(N log k) for total N nodes across k lists.
- Time complexity: O(N log k)
- Space complexity: O(k)
- Repeatedly merge pairs of lists until one remains.
- merge_two standard sorted merge.
- O(N log k) without heap.
- Time complexity: O(N log k)
- Space complexity: O(1)
Intervals#
43. Insert Interval (Leetcode:57)#
Also in DSA Patterns
Problem 2. Insert Interval — 04. Overlapping Intervals (may include extra approaches and complexity analysis).
Problem Statement
You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti.
You are also given an interval newInterval = [start, end] that represents the start and end of another interval.
Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return intervals after the insertion.
Note that you don't need to modify intervals in-place. You can make a new array and return it.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Example 2:
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
Constraints:
0 <= intervals.length <= 10^4
intervals[i].length == 2
0 <= starti <= endi <= 10^5
intervals is sorted by starti in ascending order.
newInterval.length == 2
0 <= start <= end <= 10^5
Code and Explanation
- Three cases: New interval before, after, or overlapping existing ones.
- Build result list: Insert merged interval when overlap region ends.
- Single pass through intervals.
- O(n) time if intervals already sorted.
- Time complexity: O(n)
- Space complexity: O(n)
44. Meeting Rooms (Leetcode:252)#
Also in DSA Patterns
Meeting Rooms — 10. Greedy Algorithm (may include extra approaches and complexity analysis).
Problem Statement
Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings.
Example 1:
Input: intervals = [[0,30],[5,10],[15,20]] Output: false
Constraints:
- 0 <= intervals.length <= 10^4
- intervals[i].length == 2
- 0 <= starti < endi <= 10^6
Code and Explanation
- Sort by meeting start.
- Compare adjacent: Overlap if next start < previous end.
- Return false on first overlap.
- Time complexity: O(n log n)
- Space complexity: O(1)
45. Meeting Rooms II (Leetcode:253)#
Also in DSA Patterns
Meeting Rooms II — 10. Greedy Algorithm (may include extra approaches and complexity analysis).
Problem Statement
Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.
Example 1:
Input: intervals = [[0,30],[5,10],[15,20]] Output: 2
Constraints:
- 1 <= intervals.length <= 10^4
- 0 <= starti < endi <= 10^6
Code and Explanation
- Sort by start; min-heap stores end times of active meetings.
- Free room: Pop heap while smallest end <= current start.
- Push current end; heap size = rooms needed.
- O(n log n).
- Time complexity: O(n log n)
- Space complexity: O(n)
- Events: +1 at start, -1 at end.
- Sort events; sweep counter of active meetings.
- Peak counter = minimum rooms.
- Same answer, event-based view.
- Time complexity: O(n log n)
- Space complexity: O(n)
46. Merge Intervals (Leetcode:56)#
Also in DSA Patterns
Problem 1. Merge Intervals — 04. Overlapping Intervals (may include extra approaches and complexity analysis).
Problem Statement
Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
Example 2:
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
Constraints:
1 <= intervals.length <= 10^4intervals[i].length == 20 <= starti <= endi <= 10^4
Code and Explanation
- Sort by start time.
- Merge if overlap: If current start <= last end, extend last interval.
- Else push new interval.
- O(n log n) from sort.
- Time complexity: O(n log n)
- Space complexity: O(n)
47. Non-overlapping Intervals (Leetcode:435)#
Also in DSA Patterns
Non-overlapping Intervals — 04. Overlapping Intervals (may include extra approaches and complexity analysis).
Problem Statement
Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Note that intervals which only touch at a point are non-overlapping. For example, [1, 2] and [2, 3] are non-overlapping.
Example 1:
Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping.
Example 2:
Input: intervals = [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.
Example 3:
Input: intervals = [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
Constraints:
1 <= intervals.length <= 105intervals[i].length == 2-5 * 104 <= starti < endi <= 5 * 104
Code and Explanation
- Sort by end time.
- Keep track of last kept interval end.
- If overlap, increment removal count; else update end.
- Max non-overlapping = n - removals.
- Time complexity: O(n log n)
- Space complexity: O(1)
Linked List#
48. Linked List Cycle (Leetcode:141)#
Also in DSA Patterns
Linked List Cycle — 02. Fast and Slow Pointers (may include extra approaches and complexity analysis).
Problem Statement
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Constraints:
The number of the nodes in the list is in the range [0, 10^4].
-10^5 <= Node.val <= 10^5
pos is -1 or a valid index in the linked-list.
Follow up:
Can you solve it using O(1) (i.e. constant) memory?
Code and Explanation
- Slow moves 1 step, fast moves 2.
- If they meet, cycle exists.
- If fast reaches null, no cycle.
- O(n) time, O(1) space — optimal.
- Time complexity: O(n)
- Space complexity: O(1)
- Track visited nodes in a set.
- Cycle if node seen again.
- Simple but O(n) extra space.
- Time complexity: O(n)
- Space complexity: O(n)
49. Merge Two Sorted Lists (Leetcode:21)#
Also in DSA Patterns
Merge Two Sorted Lists (Recursive) — 07. Linked List (may include extra approaches and complexity analysis).
Problem Statement
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example 1:
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: list1 = [], list2 = []
Output: []
Example 3:
Input: list1 = [], list2 = [0]
Output: [0]
Constraints:
- The number of nodes in both lists is in the range
[0, 50].-100 <= Node.val <= 100- Both
list1andlist2are sorted in non-decreasing order.
Code and Explanation
- Dummy head simplifies tail insertion.
- Attach smaller head node, advance that list.
- Append remainder when one list ends.
- Time complexity: O(n + m)
- Space complexity: O(1)
- Compare heads, attach smaller, recurse on rest.
- Base cases for empty lists.
- Same O(n) time, uses call stack.
- Time complexity: O(n + m)
- Space complexity: O(n + m)
50. Remove Nth Node From End of List (Leetcode:19)#
Also in DSA Patterns
Remove Nth Node From End of List — 02. Fast and Slow Pointers (may include extra approaches and complexity analysis).
Problem Statement
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 1
Output: [1]
Constraints:
The number of nodes in the list is sz.1 <= sz <= 300 <= Node.val <= 1001 <= n <= sz`
**Follow up: ** Could you do this in one pass?
Code and Explanation
- Dummy node handles deleting head edge case.
- Fast pointer is n+1 ahead of slow when fast hits end.
- Skip node after slow.
- One pass.
- Time complexity: O(n)
- Space complexity: O(1)
51. Reorder List (Leetcode:143)#
Also in DSA Patterns
Reorder List — 02. Fast and Slow Pointers (may include extra approaches and complexity analysis).
Problem Statement
You are given the head of a singly linked-list. The list can be represented as:
L0 → L1 → ... → Ln - 1 → Ln
Reorder the list to be on the following form:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → ...
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4]
Output: [1,4,2,3]
Example 2:
Input: head = [1,2,3,4,5]
Output: [1,5,2,4,3]
Constraints:
The number of nodes in the list is in the range
[1, 5 * 10^4].
1 <= Node.val <= 1000
Code and Explanation
- Step 1 — find middle with slow/fast pointers.
- Step 2 — reverse second half.
- Step 3 — merge alternating nodes from first and reversed second halves.
- O(n) time, O(1) space.
- Time complexity: O(n)
- Space complexity: O(1)
52. Reverse Linked List (Leetcode:206)#
Also in DSA Patterns
Reverse Linked List — 07. Linked List (may include extra approaches and complexity analysis).
Problem Statement
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5] Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2] Output: [2,1]
Example 3:
Input: head = [] Output: []
Constraints:
- The number of nodes in the list is the range
[0, 5000].-5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
Code and Explanation
- Three pointers:
prev,curr,next. - Reverse link: Point
curr.nexttoprev, shift all forward. - Return
prevas new head. - O(n) time, O(1) space.
- Time complexity: O(n)
- Space complexity: O(1)
- Base: Empty or single node returns itself.
- Recurse on tail, then point tail back to current.
- Clear current.next.
- O(n) time, O(n) stack space.
- Time complexity: O(n)
- Space complexity: O(n)
Matrix#
53. Rotate Image (Leetcode:48)#
Also in DSA Patterns
Rotate Image — 21. Math and Geometry (may include extra approaches and complexity analysis).
Problem Statement
You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees clockwise in place.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[7,4,1],[8,5,2],[9,6,3]]
Constraints:
- n == matrix.length == matrix[i].length
- 1 <= n <= 20
- -1000 <= matrix[i][j] <= 1000
Code and Explanation
- Transpose across diagonal swaps
[i][j]with[j][i]. - Reverse each row for 90° clockwise rotation.
- In-place O(n²).
- Time complexity: O(n²)
- Space complexity: O(1)
54. Set Matrix Zeroes (Leetcode:73)#
Also in DSA Patterns
Set Matrix Zeroes — 21. Math and Geometry (may include extra approaches and complexity analysis).
Problem Statement
Given an m x n integer matrix, if an element is 0, set its entire row and column to 0's. You must do it in place.
Example 1:
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]] Output: [[1,0,1],[0,0,0],[1,0,1]]
Constraints:
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 200
- -2^31 <= matrix[i][j] <= 2^31 - 1
Code and Explanation
- Use first row/col as flags for zero rows/columns.
- Remember if first row/col themselves had zeros.
- Mark from inner cells, apply marks, fix first row/col last.
- O(mn) time, O(1) space.
- Time complexity: O(m × n)
- Space complexity: O(1)
55. Spiral Matrix (Leetcode:54)#
Also in DSA Patterns
Spiral Matrix — 21. Math and Geometry (may include extra approaches and complexity analysis).
Problem Statement
Given an m x n matrix, return all elements of the matrix in spiral order.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5]
Constraints:
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
Code and Explanation
- Four boundaries: top, bottom, left, right.
- Traverse right, down, left, up; shrink bounds.
- Stop when bounds cross.
- Time complexity: O(m × n)
- Space complexity: O(1)
Sliding Window#
56. Longest Repeating Character Replacement (Leetcode:424)#
Problem Statement
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.
Return the length of the longest substring containing the same letter you can get after performing the above operations.
Example 1:
Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa.
Example 2:
Input: s = "AABABBA", k = 1 Output: 4 Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA". The substring "BBBB" has the longest repeating letters, which is 4.
Constraints:
1 <= s.length <= 10^5sconsists of only uppercase English letters.0 <= k <= s.length
Code and Explanation
- Window valid if
length - count(most_frequent_char) <= k. - Expand right; shrink left while invalid.
- Track best window size.
- Time complexity: O(n)
- Space complexity: O(1)
57. Longest Substring Without Repeating Characters (Leetcode:3)#
Problem Statement
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with length 3.
Constraints:
- 0 <= s.length <= 5 * 10^4
- s consists of English letters, digits, symbols and spaces
Code and Explanation
- Expand right, track last index of each char in map.
- If duplicate inside window, move left past previous occurrence.
- Update max window length each step.
- O(n) time.
- Time complexity: O(n)
- Space complexity: O(min(n, charset))
58. Minimum Window Substring (Leetcode:76)#
Also in DSA Patterns
Minimum Window Substring — 03. Sliding Window (may include extra approaches and complexity analysis).
Problem Statement
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".
The testcases will be generated such that the answer is unique.
Example 1:
Input: s = "ADOBECODEBANC", t = "ABC" Output: "BANC" Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
Example 2:
Input: s = "a", t = "a" Output: "a" Explanation: The entire string s is the minimum window.
Example 3:
nput: s = "a", t = "aa" Output: "" Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string.
Constraints:
m == s.lengthn == t.length1 <= m, n <= 105sandtconsist of uppercase and lowercase English letters.
Follow up:
Could you find an algorithm that runs in O(m + n) time?
Code and Explanation
- The window size remains constant throughout the process.
- The window moves from the beginning of the sequence to the end, sliding one element at a time.
- At each step, the next element is added, and the element that is no longer within the window is removed.
- The window expands or contracts depending on certain conditions.
- The size of the window is not fixed and can change during traversal.
Stack#
59. Valid Parentheses (Leetcode:20)#
Also in DSA Patterns
Valid Parentheses — 08. Stack (may include extra approaches and complexity analysis).
Problem Statement
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()" Output: true
Example 2:
Input: s = "()[]{}" Output: true
Example 3:
Input: s = "(]" Output: false
Example 4:
Input: s = "([])" Output: true
Example 5:
Input: s = "([)]" Output: false
Constraints:
1 <= s.length <= 104sconsists of parentheses only'()[]{}'.
Code and Explanation
- Push opening brackets.
- On closing, stack must match top.
- Valid iff stack empty at end.
- Time complexity: O(n)
- Space complexity: O(n)
Trees#
60. Binary Tree Level Order Traversal (Leetcode:102)#
Also in DSA Patterns
Binary Tree Level Order Traversal — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]]
Example 2:
Input: root = [1] Output: [[1]]
Example 3:
Input: root = [] Output: []
Constraints:
- The number of nodes in the tree is in the range
[0, 2000].-1000 <= Node.val <= 1000
Code and Explanation
- Queue starts with root.
- Snapshot queue size each iteration = current level width.
- Collect values, enqueue children.
- Time complexity: O(n)
- Space complexity: O(n)
61. Binary Tree Maximum Path Sum (Leetcode:124)#
Also in DSA Patterns
Maximum Path Sum in Binary Tree — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes has an edge connecting them. A node can only appear at most once. The path sum is the sum of the node values. Given the root, return the maximum path sum of any non-empty path.
Example 1:
Input: root = [1,2,3] Output: 6 Explanation: Optimal path is 2 -> 1 -> 3 with sum 6.
Constraints:
- The number of nodes is in the range [1, 3 * 10^4]
- -1000 <= Node.val <= 1000
Code and Explanation
- At each node, best path through node = left_gain + val + right_gain.
- Return to parent only one-sided gain: val + max(left, right).
- Global best tracks maximum anywhere in tree.
- Time complexity: O(n)
- Space complexity: O(h)
62. Construct Binary Tree from Preorder and Inorder Traversal (Leetcode:105)#
Also in DSA Patterns
Construct Binary Tree from Preorder and Inorder Traversal — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.
Example 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] Output: [3,9,20,null,null,15,7]
Constraints:
- 1 <= preorder.length <= 3000
- inorder.length == preorder.length
- -3000 <= preorder[i], inorder[i] <= 3000
- preorder and inorder consist of unique values
- Each value appears once in both arrays
Code and Explanation
- Precompute inorder positions: Build
in_index = {value: index}frominorder. When we pick a root from preorder, this map instantly tells us where that value splits the inorder array into left and right parts. - Shared preorder pointer:
pre_idxreads roots in preorder order (root → left subtree → right subtree). Each recursive call consumes exactly one preorder value — that value is always the root of the subtree being built. - Recurse on index ranges, not slices:
helper(left, right)builds the tree for the inorder segment[left..right]. Ifleft > right, the segment is empty → returnNone. - Split using the root's inorder index: After creating
rootfrompreorder[pre_idx], look upmid = in_index[root_val]. Left subtree covers inorder indices[left, mid-1]; right covers[mid+1, right]. No list copying. - Why this is optimal: Each node is visited once with O(1) hash lookups — no repeated slicing or
.index()calls. - Time complexity: O(n)
- Space complexity: O(n)
- Root is always
preorder[0]. Find it ininorderat indexmid. - Left subtree:
preorder[1:mid+1]pairs withinorder[:mid]. - Right subtree:
preorder[mid+1:]pairs withinorder[mid+1:]. - Easy to understand but O(n²) from slicing and
.index()at every level. - Time complexity: O(n²)
- Space complexity: O(n²)
63. Invert Binary Tree (Leetcode:226)#
Also in DSA Patterns
Invert Binary Tree — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given the root of a binary tree, invert the tree, and return its root.
Example 1:
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Explanation:
Example 2:
Input: root = [2,1,3]
Output: [2,3,1]
Example 3:
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range
[0, 100].-100 <= Node.val <= 100
Code and Explanation
- Swap left and right at each node recursively.
- Post-order: invert children then assign.
- Time complexity: O(n)
- Space complexity: O(h)
- Queue nodes; swap children when dequeuing.
- Enqueue swapped children for later processing.
- Time complexity: O(n)
- Space complexity: O(n)
64. Kth Smallest Element in a BST (Leetcode:230)#
Also in DSA Patterns
Kth Smallest Element in a BST — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.
Example 1:
Input: root = [3,1,4,null,2], k = 1 Output: 1
Constraints:
- The number of nodes is n where 1 <= k <= n <= 10^4
- 0 <= Node.val <= 10^4
Code and Explanation
- Push left spine onto stack.
- Pop, visit, go right.
- Stop at kth pop.
- Time complexity: O(h + k)
- Space complexity: O(h)
- Inorder visits BST in sorted order.
- Increment count on visit; return at k.
- Time complexity: O(h + k)
- Space complexity: O(h)
65. Lowest Common Ancestor of a Binary Search Tree (Leetcode:235)#
Also in DSA Patterns
Lowest Common Ancestor of a Binary Search Tree — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes p and q in the BST. The LCA is defined as the lowest node that has both p and q as descendants.
Example 1:
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 Output: 6 Explanation: LCA of nodes 2 and 8 is 6.
Constraints:
- The number of nodes is in the range [2, 10^5]
- -10^9 <= Node.val <= 10^9
- All Node.val are unique
- p != q
- p and q exist in the BST
Code and Explanation
- Both targets smaller → go left; both larger → go right.
- Otherwise current node is LCA.
- Uses BST ordering — no full tree search.
- Time complexity: O(h)
- Space complexity: O(1)
- Same BST logic recursively.
- Recurse left or right based on values vs root.
- Return node where paths diverge.
- Time complexity: O(h)
- Space complexity: O(h)
66. Maximum Depth of Binary Tree (Leetcode:104)#
Also in DSA Patterns
Maximum Depth of Binary Tree — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root down to the farthest leaf.
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: 3
Constraints:
- The number of nodes is in the range [0, 10^4]
- -100 <= Node.val <= 100
Code and Explanation
- Base case: Empty node → depth 0.
- Recurse on children; return 1 + max(left, right).
- Simple post-order height computation.
- Time complexity: O(n)
- Space complexity: O(h)
- Queue level-order traversal.
- Increment depth after processing each level's nodes.
- Avoids recursion depth limits.
- Time complexity: O(n)
- Space complexity: O(n)
67. Same Tree (Leetcode:100)#
Also in DSA Patterns
Same Tree — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two trees are the same if they are structurally identical and nodes have the same value.
Example 1:
Input: p = [1,2,3], q = [1,2,3] Output: true
Constraints:
- The number of nodes is in the range [0, 100]
- -10^4 <= Node.val <= 10^4
Code and Explanation
- Both null → true; one null → false.
- Values must match; recurse on both children.
- Time complexity: O(n)
- Space complexity: O(h)
68. Subtree of Another Tree (Leetcode:572)#
Problem Statement
Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot, and false otherwise.
Example 1:
Input: root = [3,4,5,1,2], subRoot = [4,1,2] Output: true
Constraints:
- The number of nodes in the root tree is in the range [1, 2000]
- The number of nodes in the subRoot tree is in the range [1, 1000]
- -10^4 <= Node.val <= 10^4
Code and Explanation
- At each node in root, test if subtree matches subRoot.
- same() compares structure and values.
- DFS left/right if no match here.
- Time complexity: O(m × n)
- Space complexity: O(h)
69. Validate Binary Search Tree (Leetcode:98)#
Also in DSA Patterns
Validate Binary Search Tree — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows: the left subtree of a node contains only nodes with keys less than the node's key, and the right subtree only nodes with keys greater than the node's key.
Example 1:
Input: root = [2,1,3] Output: true
Constraints:
- The number of nodes is in the range [1, 10^4]
- -2^31 <= Node.val <= 2^31 - 1
Code and Explanation
- Pass valid (min, max) range down recursion.
- Node must satisfy min < val < max.
- Left child max becomes current val; right child min becomes current val.
- Time complexity: O(n)
- Space complexity: O(h)
- BST inorder is strictly increasing.
- Track previous visited value.
- Invalid if current <= prev.
- Time complexity: O(n)
- Space complexity: O(h)
Tries#
70. Design Add and Search Words Data Structure (Leetcode:211)#
Also in DSA Patterns
Add and Search Word — 19. Tries (may include extra approaches and complexity analysis).
Problem Statement
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary class:
WordDictionary()Initializes the object.void addWord(word)Addswordto the data structure, it can be matched later.bool search(word)Returnstrueif there is any string in the data structure that matcheswordorfalseotherwise.wordmay contain dots'.'where dots can be matched with any letter.
Example:
Input ["WordDictionary","addWord","addWord","addWord","search","search","search","search"] [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]] Output [null,null,null,null,false,true,true,true] Explanation WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord("bad"); wordDictionary.addWord("dad"); wordDictionary.addWord("mad"); wordDictionary.search("pad"); // return False wordDictionary.search("bad"); // return True wordDictionary.search(".ad"); // return True wordDictionary.search("b.."); // return True
Constraints:
1 <= word.length <= 25wordinaddWordconsists of lowercase English letters.wordinsearchconsist of'.'or lowercase English letters.- There will be at most
2dots inwordforsearchqueries.- At most
104calls will be made toaddWordandsearch.
Code and Explanation
- Insert words into trie normally.
- Search: on '.', try all children recursively.
- Match succeeds at end-of-word flag.
- Time complexity: O(26^L) worst
- Space complexity: O(total chars)
71. Implement Trie (Prefix Tree) (Leetcode:208)#
Also in DSA Patterns
Implement Trie (Prefix Tree) — 19. Tries (may include extra approaches and complexity analysis).
Problem Statement
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
Trie()Initializes the trie object.void insert(String word)Inserts the stringwordinto the trie.boolean search(String word)Returnstrueif the stringwordis in the trie (i.e., was inserted before), andfalseotherwise.boolean startsWith(String prefix)Returnstrueif there is a previously inserted stringwordthat has the prefixprefix, andfalseotherwise.
Example 1:
Input ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] Output [null, null, true, false, true, null, true]
Explanation Trie 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
Constraints:
1 <= word.length, prefix.length <= 2000wordandprefixconsist only of lowercase English letters.- At most
3 * 104calls in total will be made toinsert,search, andstartsWith.
Code and Explanation
- Each node has char → child map and end flag.
- insert walks/creates path; search requires end flag; startsWith only needs path.
- Time complexity: O(L) per op
- Space complexity: O(total chars)
72. Word Search II (Leetcode:212)#
Also in DSA Patterns
Word Search II — 19. Tries (may include extra approaches and complexity analysis).
Problem Statement
Given an m x n board of characters and a list of strings words, return all words on the board.
Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example 1:
Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"] Output: ["eat","oath"]
Example 2:
Input: board = [["a","b"],["c","d"]], words = ["abcb"] Output: []
Constraints:
m == board.lengthn == board[i].length1 <= m, n <= 12board[i][j]is a lowercase English letter.1 <= words.length <= 3 * 1041 <= words[i].length <= 10words[i]consists of lowercase English letters.- All the strings of
wordsare unique.
Code and Explanation
- Build trie of all words.
- DFS board while walking trie; prune when prefix missing.
- Collect word at trie node; mark found to dedupe.
- Time complexity: O(m × n × 4^L)
- Space complexity: O(total chars)
Two Pointers#
73. 3Sum (Leetcode:15)#
Also in DSA Patterns
3Sum — 01. Two Pointers (may include extra approaches and complexity analysis).
Problem Statement
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation: The distinct triplets are [-1,0,1] and [-1,-1,2].
Example 2:
Input: nums = [0,1,1] Output: []
Example 3:
Input: nums = [0,0,0] Output: [[0,0,0]]
Constraints:
3 <= nums.length <= 3000-10^5 <= nums[i] <= 10^5
Code and Explanation
- Sort first: Enables two-pointer search and duplicate skipping.
- Fix one number at
i: Setleft = i+1,right = n-1, find pairs summing to-nums[i]. - Skip duplicates: After finding a triplet or advancing
i, skip equal values. - Time complexity: O(n²)
- Space complexity: O(1)
74. Container With Most Water (Leetcode:11)#
Also in DSA Patterns
Container With Most Water — 01. Two Pointers (may include extra approaches and complexity analysis).
Problem Statement
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
Example 1:
Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The max area of water the container can contain is 49.
Example 2:
Input: height = [1,1] Output: 1
Constraints:
n == height.length2 <= n <= 10^50 <= height[i] <= 10^4
Code and Explanation
- Start wide:
left = 0,right = n-1. - Area formula: Height =
min(height[left], height[right]); width =right - left. - Move shorter side: Advance the pointer at the shorter wall to seek more area.
- Why: Keeping the shorter side fixes the height cap. O(n) time.
- Time complexity: O(n)
- Space complexity: O(1)
75. Valid Palindrome (Leetcode:125)#
Also in DSA Patterns
Valid Palindrome — 01. Two Pointers (may include extra approaches and complexity analysis).
Problem Statement
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Given a string s, return true if it is a palindrome, or false otherwise.
Example 1:
Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome.
Constraints:
- 1 <= s.length <= 2 * 10^5
- s consists only of printable ASCII characters
Code and Explanation
- Move inward skipping non-alphanumeric.
- Compare lowercased chars.
- O(n) time, O(1) space.
- Time complexity: O(n)
- Space complexity: O(1)
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Input: head = [1,2]
Output: [2,1]
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]
Input: board = [["a","b"],["c","d"]], words = ["abcb"]
Output: []