NeetCode 150#
The NeetCode 150 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. Find the Duplicate Number (Leetcode:287)#
Also in DSA Patterns
Find the Duplicate Number — 02. Fast and Slow Pointers (may include extra approaches and complexity analysis).
Problem Statement
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
There is only one repeated number in nums, return this repeated number.
You must solve the problem without modifying the array nums and using only constant extra space.
Example 1:
Input: nums = [1,3,4,2,2]
Output: 2
Example 2:
Input: nums = [3,1,3,4,2]
Output: 3
Example 3:
Input: nums = [3,3,3,3,3]
Output: 3
Constraints:
1 <= n <= 105
nums.length == n + 1
1 <= nums[i] <= n
All the integers innumsappear only once except for precisely one integer which appears two or more times.
Follow up:
How can we prove that at least one duplicate number must exist in
nums?
Can you solve the problem in linear runtime complexity?
Code and Explanation
- The slow pointer moves one step at a time.
- The fast pointer moves two steps at a time.
- Cycle Detection: If a cycle exists, the fast pointer will meet the slow pointer inside the cycle.
- Middle Element: The slow pointer will be at the middle when the fast pointer reaches the end.
- Pattern Matching: Helps detect patterns like palindromes by dividing the structure into two parts.
4. Gas Station (Leetcode:134)#
Also in DSA Patterns
Gas Station — 10. Greedy Algorithm (may include extra approaches and complexity analysis).
Problem Statement
There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique.
Example 1:
Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2] Output: 3 Explanation: Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index.
Example 2:
Input: gas = [2,3,4], cost = [3,4,3] Output: -1 Explanation: You can't start at station 0 or 1, as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. Therefore, you can't travel around the circuit once no matter where you start.
Constraints:
n == gas.length == cost.length1 <= n <= 1050 <= gas[i], cost[i] <= 104- The input is generated such that the answer is unique.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
5. 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)
6. Happy Number (Leetcode:202)#
Also in DSA Patterns
Happy Number — 02. Fast and Slow Pointers (may include extra approaches and complexity analysis).
Problem Statement
Write an algorithm to determine if a number n is happy.
A happy number is a number defined by the following process:
- Starting with any positive integer, replace the number by the sum of the squares of its digits.
- Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
- Those numbers for which this process ends in 1 are happy.
Return true if n is a happy number, and false if not.
Example 1:
Input: n = 19
Output: true
Explanation:
1² + 9² = 82
8² + 2² = 68
6² + 8² = 100
1² + 0² + 0² = 1
Example 2:
Input: n = 2
Output: false
Constraints:
1 <= n <= 2^31 - 1
Code and Explanation
- The slow pointer moves one step at a time.
- The fast pointer moves two steps at a time.
- Cycle Detection: If a cycle exists, the fast pointer will meet the slow pointer inside the cycle.
- Middle Element: The slow pointer will be at the middle when the fast pointer reaches the end.
- Pattern Matching: Helps detect patterns like palindromes by dividing the structure into two parts.
7. 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)
8. Jump Game II (Leetcode:45)#
Also in DSA Patterns
Jump Game II — 10. Greedy Algorithm (may include extra approaches and complexity analysis).
Problem Statement
You are given a 0-indexed array of integers nums of length n. You are initially positioned at index 0.
Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at index i, you can jump to any index (i + j) where:
0 <= j <= nums[i]andi + j < n
Return the minimum number of jumps to reach index n - 1. The test cases are generated such that you can reach index n - 1.
Example 1:
Input: nums = [2,3,1,1,4] Output: 2 Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: nums = [2,3,0,1,4] Output: 2
Constraints:
1 <= nums.length <= 1040 <= nums[i] <= 1000- It's guaranteed that you can reach
nums[n - 1].
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
9. Longest Consecutive Sequence (Leetcode:128)#
Problem Statement
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2] Output: 4 Explanation: The longest consecutive sequence is [1, 2, 3, 4].
Constraints:
- 0 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
Code and Explanation
- Insert all numbers into a set.
- Only start from sequence beginnings: Skip if
num-1exists. - Extend forward: Count while
num+lengthin set. - Track max length. O(n) average time.
- Time complexity: O(n)
- Space complexity: O(n)
10. 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)
11. Top K Frequent Elements (Leetcode:347)#
Also in DSA Patterns
Top K Frequent Elements — 15. Heaps (may include extra approaches and complexity analysis).
Problem Statement
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
Example 2:
Input: nums = [1], k = 1 Output: [1]
Constraints:
1 <= nums.length <= 105-104 <= nums[i] <= 104kis in the range[1, the number of unique elements in the array].- It is guaranteed that the answer is unique.
Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
Code and Explanation
- Count frequencies with Counter.
- heapq.nlargest(k, keys, key=counts.get) returns top k.
- Simple and effective.
- Time complexity: O(n log k)
- Space complexity: O(n)
- Bucket index = frequency.
- Scan buckets high to low until k elements collected.
- O(n) when frequency range bounded by n.
- Time complexity: O(n)
- Space complexity: O(n)
12. 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)
13. 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#
14. 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)
15. Combination Sum II (Leetcode:40)#
Also in DSA Patterns
Combination Sum II (avoid duplicates) — 12. Backtracking (may include extra approaches and complexity analysis).
Problem Statement
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.
Each number in candidates may only be used once in the combination.
Note: The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8 Output: [ [1,1,6], [1,2,5], [1,7], [2,6] ]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5 Output: [ [1,2,2], [5] ]
Constraints:
1 <= candidates.length <= 1001 <= candidates[i] <= 501 <= target <= 30
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
16. Generate Parentheses (Leetcode:22)#
Also in DSA Patterns
Generate Parentheses — 12. Backtracking (may include extra approaches and complexity analysis).
Problem Statement
Given n pairs of parentheses, generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
Constraints:
1 <= n <= 8
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
17. 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.
18. N-Queens (Leetcode:51)#
Also in DSA Patterns
N-Queens — 12. Backtracking (may include extra approaches and complexity analysis).
Problem Statement
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order**.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
Example 1:
Input: n = 4 Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
Example 2:
Input: n = 1 Output: [["Q"]]
Constraints:
1 <= n <= 9
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
19. Palindrome Partitioning (Leetcode:131)#
Also in DSA Patterns
Palindrome Partitioning — 12. Backtracking (may include extra approaches and complexity analysis).
Problem Statement
Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.
Example 1:
Input: s = "aab" Output: [["a","a","b"],["aa","b"]]
Example 2:
Input: s = "a" Output: [["a"]]
Constraints:
1 <= s.length <= 16scontains only lowercase English letters.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
20. 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.
21. Subsets (Leetcode:78)#
Also in DSA Patterns
Subsets — 12. Backtracking (may include extra approaches and complexity analysis).
Problem Statement
Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,3] Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0] Output: [[],[0]]
Constraints:
1 <= nums.length <= 10-10 <= nums[i] <= 10- All the numbers of
numsare unique.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
22. Subsets II (Leetcode:90)#
Also in DSA Patterns
Subsets II — 12. Backtracking (may include extra approaches and complexity analysis).
Problem Statement
Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets.
Example 1:
Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
Constraints:
1 <= nums.length <= 10-10 <= nums[i] <= 10
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
23. 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#
24. Binary Search (Leetcode:704)#
Also in DSA Patterns
Binary Search — 09. Binary Search (may include extra approaches and complexity analysis).
Problem Statement
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4 Explanation: 9 exists in nums and its index is 4
Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2 Output: -1 Explanation: 2 does not exist in nums so return -1
Constraints:
1 <= nums.length <= 104-104 < nums[i], target < 104- All the integers in
numsare unique.numsis sorted in ascending order.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
25. 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)
26. Koko Eating Bananas (Leetcode:875)#
Also in DSA Patterns
Koko Eating Bananas — 09. Binary Search (may include extra approaches and complexity analysis).
Problem Statement
Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.
Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return the minimum integer k such that she can eat all the bananas within h hours.
Example 1:
Input: piles = [3,6,7,11], h = 8 Output: 4
Example 2:
Input: piles = [30,11,23,4,20], h = 5 Output: 30
Example 3:
Input: piles = [30,11,23,4,20], h = 6 Output: 23
Constraints:
1 <= piles.length <= 104piles.length <= h <= 1091 <= piles[i] <= 109
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
27. Median of Two Sorted Arrays (Leetcode:4)#
Problem Statement
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Example 1:
Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Constraints:
nums1.length == mnums2.length == n0 <= m <= 10000 <= n <= 10001 <= m + n <= 2000-106 <= nums1[i], nums2[i] <= 106
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
28. Search a 2D Matrix (Leetcode:74)#
Also in DSA Patterns
Search a 2D Matrix — 09. Binary Search (may include extra approaches and complexity analysis).
Problem Statement
You are given an m x n integer matrix matrix with the following two properties:
- Each row is sorted in non-decreasing order.
- The first integer of each row is greater than the last integer of the previous row.
Given an integer target, return true if target is in matrix or false otherwise.
You must write a solution in O(log(m * n)) time complexity.
Example 1:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 Output: true
Example 2:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 Output: false
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 100-104 <= matrix[i][j], target <= 104
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
29. 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#
30. 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)
31. 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)
32. 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)
33. 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)
34. Single Number (Leetcode:136)#
Also in DSA Patterns
Single Number — 06. Bit Manipulation (may include extra approaches and complexity analysis).
Problem Statement
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Input: nums = [1]
Output: 1
Constraints:
1 <= nums.length <= 3 * 10^4
-3 * 10^4 <= nums[i] <= 3 * 10^4
Each element appears twice except for one element which appears only once.
35. 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#
36. Design Twitter (Leetcode:355)#
Also in DSA Patterns
Design Twitter — 22. Challenge Yourself (may include extra approaches and complexity analysis).
Problem Statement
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and see the 10 most recent tweet ids in the user's news feed.
Implement the Twitter class:
Twitter()Initializes your twitter object.void postTweet(int userId, int tweetId)Creates a new tweet with IDtweetIdby the useruserId. Each call will be made with a unique tweetId.List<Integer> getNewsFeed(int userId)Retrieves the 10 most recent tweet IDs in the user's feed. Each item must be posted by users who the user followed or by the user themself. Tweets must be ordered from most recent to least recent.void follow(int followerId, int followeeId)The user with IDfollowerIdfollows the user with IDfolloweeId.void unfollow(int followerId, int followeeId)The user with IDfollowerIdunfollowed the user with IDfolloweeId.
Example 1:
Input: ["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"]
[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]
Output: [null, null, [5], null, null, [6, 5], null, [5]]
Constraints:
1 <= userId, followerId, followeeId <= 5000 <= tweetId <= 104- All tweets have unique IDs.
- At most
3 * 104calls will be made topostTweet,getNewsFeed,follow, andunfollow.
Patterns: Hash Map · Heap · K-way Merge
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
37. 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)
38. LRU Cache (Leetcode:146)#
Also in DSA Patterns
LRU Cache — 22. Challenge Yourself (may include extra approaches and complexity analysis).
Problem Statement
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
Implement the LRUCache class:
LRUCache(int capacity)Initialize the LRU cache with positive sizecapacity.int get(int key)Return the value of thekeyif the key exists, otherwise return-1.void put(int key, int value)Update the value of thekeyif the key exists. Otherwise, add thekey-valuepair to the cache. If the number of keys exceeds thecapacityfrom this operation, evict the least recently used key.
The functions get and put must each run in O(1) average time complexity.
Example 1:
Input: ["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
Output: [null, null, null, 1, null, -1, null, -1, 3, 4]
Constraints:
1 <= capacity <= 30000 <= key <= 1040 <= value <= 105- At most
2 * 105calls will be made togetandput.
Patterns: Hash Map · Linked List
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
39. Min Stack (Leetcode:155)#
Also in DSA Patterns
Min Stack — 08. Stack (may include extra approaches and complexity analysis).
Problem Statement
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack()initializes the stack object.void push(int val)pushes the elementvalonto the stack.void pop()removes the element on the top of the stack.int top()gets the top element of the stack.int getMin()retrieves the minimum element in the stack.
You must implement a solution with O(1) time complexity for each function.
Example 1:
Input ["MinStack","push","push","push","getMin","pop","top","getMin"] [[],[-2],[0],[-3],[],[],[],[]] Output [null,null,null,null,-3,null,0,-2] Explanation MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2
Constraints:
-231 <= val <= 231 - 1- Methods
pop,topandgetMinoperations will always be called on non-empty stacks.- At most
3 * 104calls will be made topush,pop,top, andgetMin.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
40. 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)
41. Time Based Key-Value Store (Leetcode:981)#
Also in DSA Patterns
Time Based Key-Value Store — 22. Challenge Yourself (may include extra approaches and complexity analysis).
Problem Statement
Design a time-based key-value data structure that can store multiple values for the same key at different timestamps and retrieve the key's value at a certain timestamp.
Implement the TimeMap class:
TimeMap()Initializes the object.void set(String key, String value, int timestamp)Stores the keykeywith the valuevalueat the given timetimestamp.String get(String key, int timestamp)Returns a value such thatsetwas called previously, withtimestamp_prev <= timestamp. If there are multiple such values, it returns the value associated with the largesttimestamp_prev. If there are no values, it returns"".
Example 1:
Input: ["TimeMap", "set", "get", "get", "set", "get", "get"]
[[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]]
Output: [null, null, "bar", "bar", null, "bar2", "bar2"]
Constraints:
1 <= key.length, value.length <= 100keyandvalueconsist of lowercase English letters and digits.1 <= timestamp <= 107- All timestamps of
setare strictly increasing.- At most
2 * 105calls will be made tosetandget.
Patterns: Hash Map · Binary Search
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
Dynamic Programming#
42. 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)
43. Best Time to Buy and Sell Stock with Cooldown (Leetcode:309)#
Also in DSA Patterns
Best Time to Buy and Sell Stock with Cooldown — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
Given prices, maximize profit with unlimited transactions, but after you sell your stock, you cannot buy on the next day (one-day cooldown). You may not hold more than one share.
Example 1:
Input: prices = [1,2,3,0,2]
Output: 3
Explanation: buy 1 sell 2, cooldown, buy 0 sell 2.
Example 2:
Input: prices = [1]
Output: 0
Constraints:
1 <= prices.length <= 50000 <= prices[i] <= 1000
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
44. Burst Balloons (Leetcode:312)#
Also in DSA Patterns
Burst Balloons — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
Given n balloons with integers nums, bursting balloon i adds nums[i-1] * nums[i] * nums[i+1] coins (out-of-bounds treated as 1). Return maximum coins obtainable.
Example 1:
Input: nums = [3,1,5,8]
Output: 167
Example 2:
Input: nums = [1,5]
Output: 10
Constraints:
1 <= nums.length <= 5000 <= nums[i] <= 100
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
45. 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)
46. 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)
47. Coin Change II (Leetcode:518)#
Also in DSA Patterns
Coin Change I – Maximum Number of Ways — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
Given an integer array coins of distinct denominations and an integer amount, return the number of combinations that make up that amount. Each coin may be used an unlimited number of times. The answer fits in a 32-bit integer.
Example 1:
Input: amount = 5, coins = [1,2,5]
Output: 4
Explanation: 5=5, 5=2+2+1, 5=2+1+1+1, 5=1+1+1+1+1.
Example 2:
Input: amount = 3, coins = [2]
Output: 0
Constraints:
1 <= coins.length <= 3001 <= coins[i] <= 50000 <= amount <= 5000
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
48. 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)
49. Distinct Subsequences (Leetcode:115)#
Problem Statement
Given two strings s and t, return the number of distinct subsequences of s which equals t.
The test cases are generated so that the answer fits on a 32-bit signed integer.
Example 1:
Input: s = "rabbbit", t = "rabbit" Output: 3 Explanation: As shown below, there are 3 ways you can generate "rabbit" from s.
**rabb**b**it****ra**b**bbit****rab**b**bit**
Example 2:
Input: s = "babgbag", t = "bag" Output: 5 Explanation: As shown below, there are 5 ways you can generate "bag" from s.
**ba**b**g**bag**ba**bgba**g****b**abgb**ag**ba**b**gb**ag**babg**bag**
Constraints:
1 <= s.length, t.length <= 1000
sandtconsist of English letters.
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def numDistinct(self, s: str, t: str) -> int:
cache = {}
for i in range(len(s) + 1):
cache[(i, len(t))] = 1
for j in range(len(t)):
cache[(len(s), j)] = 0
for i in range(len(s) - 1, -1, -1):
for j in range(len(t) - 1, -1, -1):
if s[i] == t[j]:
cache[(i, j)] = cache[(i + 1, j + 1)] + cache[(i + 1, j)]
else:
cache[(i, j)] = cache[(i + 1, j)]
return cache[(0, 0)]
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
50. Edit Distance (Leetcode:72)#
Also in DSA Patterns
Edit Distance — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
Given two strings word1 and word2, return the minimum number of operations to convert word1 to word2. Allowed operations: insert, delete, or replace a character.
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Example 2:
Input: word1 = "intention", word2 = "execution"
Output: 5
Constraints:
0 <= word1.length, word2.length <= 500word1andword2consist of lowercase English letters.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
51. 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)
52. 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)
53. Interleaving String (Leetcode:97)#
Problem Statement
Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2.
An interleaving of two strings s and t is a configuration where s and t are divided into n and m substrings respectively, such that:
s = s_1_ + s_2_ + ... + s_n_
t = t_1_ + t_2_ + ... + t_m_
|n - m| <= 1The interleaving is
s_1_ + t_1_ + s_2_ + t_2_ + s_3_ + t_3_ + ...ort_1_ + s_1_ + t_2_ + s_2_ + t_3_ + s_3_ + ...
Note: a + b is the concatenation of strings a and b.
Example 1:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" Output: true Explanation: One way to obtain s3 is: Split s1 into s1 = "aa" + "bc" + "c", and s2 into s2 = "dbbc" + "a". Interleaving the two splits, we get "aa" + "dbbc" + "bc" + "a" + "c" = "aadbbcbcac". Since s3 can be obtained by interleaving s1 and s2, we return true.
Example 2:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" Output: false Explanation: Notice how it is impossible to interleave s2 with any other string to obtain s3.
Example 3:
Input: s1 = "", s2 = "", s3 = "" Output: true
Constraints:
0 <= s1.length, s2.length <= 100
0 <= s3.length <= 200
s1,s2, ands3consist of lowercase English letters.
Follow up: Could you solve it using only O(s2.length) additional memory space?
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
if len(s1) + len(s2) != len(s3):
return False
dp = [[False] * (len(s2) + 1) for i in range(len(s1) + 1)]
dp[len(s1)][len(s2)] = True
for i in range(len(s1), -1, -1):
for j in range(len(s2), -1, -1):
if i < len(s1) and s1[i] == s3[i + j] and dp[i + 1][j]:
dp[i][j] = True
if j < len(s2) and s2[j] == s3[i + j] and dp[i][j + 1]:
dp[i][j] = True
return dp[0][0]
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
54. 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))
55. Longest Increasing Path in a Matrix (Leetcode:329)#
Problem Statement
Given an m x n integers matrix, return the length of the longest increasing path in matrix.
From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).
Example 1:
Input: matrix = [[9,9,4],[6,6,8],[2,1,1]] Output: 4 Explanation: The longest increasing path is
[1, 2, 6, 9].
Example 2:
Input: matrix = [[3,4,5],[3,2,6],[2,2,1]] Output: 4 Explanation: The longest increasing path is
[3, 4, 5, 6]. Moving diagonally is not allowed.
Example 3:
Input: matrix = [[1]] Output: 1
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 200
0 <= matrix[i][j] <= 231 - 1
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
ROWS, COLS = len(matrix), len(matrix[0])
dp = {} # (r, c) -> LIP
def dfs(r, c, prevVal):
if r < 0 or r == ROWS or c < 0 or c == COLS or matrix[r][c] <= prevVal:
return 0
if (r, c) in dp:
return dp[(r, c)]
res = 1
res = max(res, 1 + dfs(r + 1, c, matrix[r][c]))
res = max(res, 1 + dfs(r - 1, c, matrix[r][c]))
res = max(res, 1 + dfs(r, c + 1, matrix[r][c]))
res = max(res, 1 + dfs(r, c - 1, matrix[r][c]))
dp[(r, c)] = res
return res
for r in range(ROWS):
for c in range(COLS):
dfs(r, c, -1)
return max(dp.values())
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
56. 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)
57. 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²)
58. 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)
59. 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)
60. Min Cost Climbing Stairs (Leetcode:746)#
Problem Statement
You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index 0, or the step with index 1.
Return the minimum cost to reach the top of the floor.
Example 1:
Input: cost = [10,15,20] Output: 15 Explanation: You will start at index 1. - Pay 15 and climb two steps to reach the top. The total cost is 15.
Example 2:
Input: cost = [1,100,1,1,1,100,1,1,100,1] Output: 6 Explanation: You will start at index 0. - Pay 1 and climb two steps to reach index 2. - Pay 1 and climb two steps to reach index 4. - Pay 1 and climb two steps to reach index 6. - Pay 1 and climb one step to reach index 7. - Pay 1 and climb two steps to reach index 9. - Pay 1 and climb one step to reach the top. The total cost is 6.
Constraints:
2 <= cost.length <= 1000
0 <= cost[i] <= 999
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
for i in range(len(cost) - 3, -1, -1):
cost[i] += min(cost[i + 1], cost[i + 2])
return min(cost[0], cost[1])
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
61. 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²)
62. Partition Equal Subset Sum (Leetcode:416)#
Also in DSA Patterns
Partition Equal Subset Sum — 12. Backtracking (may include extra approaches and complexity analysis).
Problem Statement
Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.
Example 1:
Input: nums = [1,5,11,5] Output: true Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: nums = [1,2,3,5] Output: false Explanation: The array cannot be partitioned into equal sum subsets.
Constraints:
1 <= nums.length <= 2001 <= nums[i] <= 100
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
63. Regular Expression Matching (Leetcode:10)#
Also in DSA Patterns
Regular Expression Matching — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*':
'.'Matches any single character.'*'Matches zero or more of the preceding element.
The matching should cover the entire input string. Return true if s matches p.
Example 1:
Input: s = "aa", p = "a"
Output: false
Example 2:
Input: s = "aa", p = "a*"
Output: true
Example 3:
Input: s = "ab", p = ".*"
Output: true
Constraints:
1 <= s.length <= 201 <= p.length <= 20scontains only lowercase English letters.pcontains only lowercase English letters,'.', and'*'.- It is guaranteed that for each occurrence of
'*', there is a valid preceding character.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
64. Target Sum (Leetcode:494)#
Also in DSA Patterns
Target Sum — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
Given an integer array nums and an integer target, assign each element a + or − sign so that the resulting expression equals target. Return the number of ways.
Example 1:
Input: nums = [1,1,1,1,1], target = 3
Output: 5
Example 2:
Input: nums = [1], target = 1
Output: 1
Constraints:
1 <= nums.length <= 200 <= nums[i] <= 10000 <= sum(nums[i]) <= 1000−1000 <= target <= 1000
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
65. 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)
66. 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#
67. Alien Dictionary (Leetcode:269)#
Problem Statement
There is a new alien language that uses the English alphabet. However, the order among letters is unknown. You are given a list of strings words from the alien language's dictionary, where the strings are sorted lexicographically. Derive the order of letters in this language. If the order is invalid, return an empty string.
Example 1:
Input: words = ["wrt","wrf","er","ett","rftt"] Output: "wertf"
Constraints:
- 1 <= words.length <= 100
- 1 <= words[i].length <= 100
- words[i] consists of only lowercase English letters
Code and Explanation
- Compare adjacent words to extract character order edges.
- Invalid if longer word is prefix of shorter (e.g. abc before ab).
- Kahn BFS on graph; cycle ⇒ return empty string.
- Time complexity: O(C + E)
- Space complexity: O(C + E)
68. Cheapest Flights Within K Stops (Leetcode:787)#
Problem Statement
There are n cities connected by some number of flights. You are given an array flights where flights[i] = [from_i_, to_i_, price_i_] indicates that there is a flight from city from_i_ to city to_i_ with cost price_i_.
You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.
Example 1:
Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 Output: 700 Explanation: The graph is shown above. The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.
Example 2:
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 Output: 200 Explanation: The graph is shown above. The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.
Example 3:
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0 Output: 500 Explanation: The graph is shown above. The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.
Constraints:
2 <= n <= 100
0 <= flights.length <= (n * (n - 1) / 2)
flights[i].length == 3
0 <= from_i_, to_i_ < n
from_i_ != to_i_
1 <= price_i_ <= 104There will not be any multiple flights between two cities.
0 <= src, dst, k < n
src != dst
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def findCheapestPrice(
self, n: int, flights: List[List[int]], src: int, dst: int, k: int
) -> int:
prices = [float("inf")] * n
prices[src] = 0
for i in range(k + 1):
tmpPrices = prices.copy()
for s, d, p in flights: # s=source, d=dest, p=price
if prices[s] == float("inf"):
continue
if prices[s] + p < tmpPrices[d]:
tmpPrices[d] = prices[s] + p
prices = tmpPrices
return -1 if prices[dst] == float("inf") else prices[dst]
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
69. 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)
70. 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)
71. Course Schedule II (Leetcode:210)#
Problem Statement
An n x n matrix isConnected represents cities. isConnected[i][j] = 1 if cities i and j are directly connected. A province is a group of directly or indirectly connected cities. Return the total number of provinces.
Example: isConnected = [[1,1,0],[1,1,0],[0,0,1]] → Output: 2
Constraints: 1 <= n <= 200
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
72. 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)
73. Max Area of Island (Leetcode:695)#
Problem Statement
An n x n matrix isConnected represents cities. isConnected[i][j] = 1 if cities i and j are directly connected. A province is a group of directly or indirectly connected cities. Return the total number of provinces.
Example: isConnected = [[1,1,0],[1,1,0],[0,0,1]] → Output: 2
Constraints: 1 <= n <= 200
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
74. Min Cost to Connect All Points (Leetcode:1584)#
Also in DSA Patterns
Minimum Cost to Connect All Points — 10. Greedy Algorithm (may include extra approaches and complexity analysis).
Problem Statement
You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].
The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.
Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.
Example 1:
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]] Output: 20 Explanation:
We can connect the points as shown above to get the minimum cost of 20. Notice that there is a unique path between every pair of points.
Example 2:
Input: points = [[3,12],[-2,5],[-4,1]] Output: 18
Constraints:
1 <= points.length <= 1000-106 <= xi, yi <= 106- All pairs
(xi, yi)are distinct.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
75. Network Delay Time (Leetcode:743)#
Also in DSA Patterns
Network Delay Time — 10. Greedy Algorithm (may include extra approaches and complexity analysis).
Problem Statement
You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.
We will send a signal from a given node k. Return the minimum time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.
Example 1:
Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2 Output: 2
Example 2:
Input: times = [[1,2,1]], n = 2, k = 1 Output: 1
Example 3:
Input: times = [[1,2,1]], n = 2, k = 2 Output: -1
Constraints:
1 <= k <= n <= 1001 <= times.length <= 6000times[i].length == 31 <= ui, vi <= nui != vi0 <= wi <= 100- All the pairs
(ui, vi)are unique. (i.e., no multiple edges.)
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
76. 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)
77. 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)
78. 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)
79. Reconstruct Itinerary (Leetcode:332)#
Problem Statement
An n x n matrix isConnected represents cities. isConnected[i][j] = 1 if cities i and j are directly connected. A province is a group of directly or indirectly connected cities. Return the total number of provinces.
Example: isConnected = [[1,1,0],[1,1,0],[0,0,1]] → Output: 2
Constraints: 1 <= n <= 200
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
80. Redundant Connection (Leetcode:684)#
Problem Statement
An n x n matrix isConnected represents cities. isConnected[i][j] = 1 if cities i and j are directly connected. A province is a group of directly or indirectly connected cities. Return the total number of provinces.
Example: isConnected = [[1,1,0],[1,1,0],[0,0,1]] → Output: 2
Constraints: 1 <= n <= 200
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
81. Rotting Oranges (Leetcode:994)#
Problem Statement
An n x n matrix isConnected represents cities. isConnected[i][j] = 1 if cities i and j are directly connected. A province is a group of directly or indirectly connected cities. Return the total number of provinces.
Example: isConnected = [[1,1,0],[1,1,0],[0,0,1]] → Output: 2
Constraints: 1 <= n <= 200
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
82. Surrounded Regions (Leetcode:130)#
Problem Statement
An n x n matrix isConnected represents cities. isConnected[i][j] = 1 if cities i and j are directly connected. A province is a group of directly or indirectly connected cities. Return the total number of provinces.
Example: isConnected = [[1,1,0],[1,1,0],[0,0,1]] → Output: 2
Constraints: 1 <= n <= 200
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
83. Swim in Rising Water (Leetcode:778)#
Problem Statement
You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j).
It starts raining, and water gradually rises over time. At time t, the water level is t, meaning any cell with elevation less than equal to t is submerged or reachable.
You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.
Return the minimum time until you can reach the bottom right square (n - 1, n - 1) if you start at the top left square (0, 0).
Example 1:
Input: grid = [[0,2],[1,3]] Output: 3 Explanation: At time 0, you are in grid location (0, 0). You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. You cannot reach point (1, 1) until time 3. When the depth of water is 3, we can swim anywhere inside the grid.
Example 2:
Input: grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]] Output: 16 Explanation: The final route is shown. We need to wait until time 16 so that (0, 0) and (4, 4) are connected.
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 50
0 <= grid[i][j] < n2Each value
grid[i][j]is unique.
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def swimInWater(self, grid: List[List[int]]) -> int:
N = len(grid)
visit = set()
minH = [[grid[0][0], 0, 0]] # (time/max-height, r, c)
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
visit.add((0, 0))
while minH:
t, r, c = heapq.heappop(minH)
if r == N - 1 and c == N - 1:
return t
for dr, dc in directions:
neiR, neiC = r + dr, c + dc
if (
neiR < 0
or neiC < 0
or neiR == N
or neiC == N
or (neiR, neiC) in visit
):
continue
visit.add((neiR, neiC))
heapq.heappush(minH, [max(t, grid[neiR][neiC]), neiR, neiC])
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
84. Walls and Gates (Leetcode:286)#
Problem Statement
You are given an m x n grid rooms with the following values:
-1represents a wall or an obstacle.0represents a gate.INF(2147483647) represents an empty room. We use the valueINFso that the distance to a gate is less thanINF.
Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should remain INF.
Example 1:
Input: rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]] Output: [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
Example 2:
Input: rooms = [[-1]] Output: [[-1]]
Constraints:
m == rooms.lengthn == rooms[i].length1 <= m, n <= 250rooms[i][j]is-1,0, or2^31 - 1.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
85. Word Ladder (Leetcode:127)#
Problem Statement
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:
- Every adjacent pair of words differs by a single letter.
- Every
sifor1 <= i <= kis inwordList. Note thatbeginWorddoes not need to be inwordList. sk == endWord
Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
Example 1:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: 5 Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long.
Example 2:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] Output: 0 Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
Constraints:
1 <= beginWord.length <= 10endWord.length == beginWord.length1 <= wordList.length <= 5000wordList[i].length == beginWord.lengthbeginWord,endWord, andwordList[i]consist of lowercase English letters.beginWord != endWord- All the words in
wordListare unique.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
Greedy#
86. Hand of Straights (Leetcode:846)#
Problem Statement
Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards.
Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.
Example 1:
Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3 Output: true Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]
Example 2:
Input: hand = [1,2,3,4,5], groupSize = 4 Output: false Explanation: Alice's hand can not be rearranged into groups of 4.
Constraints:
1 <= hand.length <= 104
0 <= hand[i] <= 109
1 <= groupSize <= hand.length
Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
if len(hand) % groupSize:
return False
count = {}
for n in hand:
count[n] = 1 + count.get(n, 0)
minH = list(count.keys())
heapq.heapify(minH)
while minH:
first = minH[0]
for i in range(first, first + groupSize):
if i not in count:
return False
count[i] -= 1
if count[i] == 0:
if i != minH[0]:
return False
heapq.heappop(minH)
return True
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
87. Merge Triplets to Form Target Triplet (Leetcode:1899)#
Problem Statement
A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [a_i_, b_i_, c_i_] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain.
To obtain target, you may apply the following operation on triplets any number of times (possibly zero):
Choose two indices (0-indexed)
iandj(i != j) and updatetriplets[j]to become[max(a_i_, a_j_), max(b_i_, b_j_), max(c_i_, c_j_)].For example, if
triplets[i] = [2, 5, 3]andtriplets[j] = [1, 7, 5],triplets[j]will be updated to[max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5].
Return true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise.
Example 1:
Input: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5] Output: true Explanation: Perform the following operations: - Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = [[2,5,3],[1,8,4],[2,7,5]] The target triplet [2,7,5] is now an element of triplets.
Example 2:
Input: triplets = [[3,4,5],[4,5,6]], target = [3,2,5] Output: false Explanation: It is impossible to have [3,2,5] as an element because there is no 2 in any of the triplets.
Example 3:
Input: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5] Output: true Explanation: Perform the following operations: - Choose the first and third triplets [[2,5,3],[2,3,4],[1,2,5],[5,2,3]]. Update the third triplet to be [max(2,1), max(5,2), max(3,5)] = [2,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. - Choose the third and fourth triplets [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. Update the fourth triplet to be [max(2,5), max(5,2), max(5,3)] = [5,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,5,5]]. The target triplet [5,5,5] is now an element of triplets.
Constraints:
1 <= triplets.length <= 105
triplets[i].length == target.length == 3
1 <= a_i_, b_i_, c_i_, x, y, z <= 1000
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:
good = set()
for t in triplets:
if t[0] > target[0] or t[1] > target[1] or t[2] > target[2]:
continue
for i, v in enumerate(t):
if v == target[i]:
good.add(i)
return len(good) == 3
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
88. Partition Labels (Leetcode:763)#
Problem Statement
You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string is s.
Return a list of integers representing the size of these parts.
Example 1:
Input: s = "ababcbacadefegdehijhklij" Output: [9,7,8] Explanation: The partition is "ababcbaca", "defegde", "hijhklij".
Example 2:
Input: s = "eccbbbbdec" Output: [10]
Constraints:
1 <= s.length <= 500sconsists of lowercase English letters.
Code and Explanation
- The slow pointer moves one step at a time.
- The fast pointer moves two steps at a time.
- Cycle Detection: If a cycle exists, the fast pointer will meet the slow pointer inside the cycle.
- Middle Element: The slow pointer will be at the middle when the fast pointer reaches the end.
- Pattern Matching: Helps detect patterns like palindromes by dividing the structure into two parts.
89. Valid Parenthesis String (Leetcode:678)#
Problem Statement
Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid**.
The following rules define a valid string:
Any left parenthesis
'('must have a corresponding right parenthesis')'.Any right parenthesis
')'must have a corresponding left parenthesis'('.Left parenthesis
'('must go before the corresponding right parenthesis')'.
'*'could be treated as a single right parenthesis')'or a single left parenthesis'('or an empty string"".
Example 1:
Input: s = "()" Output: true Example 2:
Input: s = "()" Output: true Example 3:*
Input: s = "())" Output:* true
Constraints:
1 <= s.length <= 100
s[i]is'(',')'or'*'.
Code and Explanation
=== "Optimal"
```python linenums="1"
# Dynamic Programming: O(n^2)
class Solution:
def checkValidString(self, s: str) -> bool:
dp = {(len(s), 0): True} # key=(i, leftCount) -> isValid
def dfs(i, left):
if i == len(s) or left < 0:
return left == 0
if (i, left) in dp:
return dp[(i, left)]
if s[i] == "(":
dp[(i, left)] = dfs(i + 1, left + 1)
elif s[i] == ")":
dp[(i, left)] = dfs(i + 1, left - 1)
else:
dp[(i, left)] = (
dfs(i + 1, left + 1) or dfs(i + 1, left - 1) or dfs(i + 1, left)
)
return dp[(i, left)]
return dfs(0, 0)
# Greedy: O(n)
class Solution:
def checkValidString(self, s: str) -> bool:
leftMin, leftMax = 0, 0
for c in s:
if c == "(":
leftMin, leftMax = leftMin + 1, leftMax + 1
elif c == ")":
leftMin, leftMax = leftMin - 1, leftMax - 1
else:
leftMin, leftMax = leftMin - 1, leftMax + 1
if leftMax < 0:
return False
if leftMin < 0: # required because -> s = ( * ) (
leftMin = 0
return leftMin == 0
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
Heap / Priority Queue#
90. K Closest Points to Origin (Leetcode:973)#
Also in DSA Patterns
K Closest Points to Origin — 15. Heaps (may include extra approaches and complexity analysis).
Problem Statement
Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).
The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).
Example 1:
Input: points = [[1,3],[-2,2]], k = 1 Output: [[-2,2]] Explanation: The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].
Example 2:
Input: points = [[3,3],[5,-1],[-2,4]], k = 2 Output: [[3,3],[-2,4]] Explanation: The answer [[-2,4],[3,3]] would also be accepted.
Constraints:
1 <= k <= points.length <= 104-104 <= xi, yi <= 104
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
91. Kth Largest Element in a Stream (Leetcode:703)#
Also in DSA Patterns
Kth Largest Element in a Stream — 15. Heaps (may include extra approaches and complexity analysis).
Problem Statement
You are part of a university admissions office and need to keep track of the kth highest test score from applicants in real-time. This helps to determine cut-off marks for interviews and admissions dynamically as new applicants submit their scores.
You are tasked to implement a class which, for a given integer k, maintains a stream of test scores and continuously returns the kth highest test score after a new score has been submitted. More specifically, we are looking for the kth highest score in the sorted list of all scores.
Implement the KthLargest class:
KthLargest(int k, int[] nums)Initializes the object with the integerkand the stream of test scoresnums.int add(int val)Adds a new test scorevalto the stream and returns the element representing thekthlargest element in the pool of test scores so far.
Example 1:
Input: ["KthLargest", "add", "add", "add", "add", "add"] [[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]] Output: [null, 4, 5, 5, 8, 8] Explanation: KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]); kthLargest.add(3); // return 4 kthLargest.add(5); // return 5 kthLargest.add(10); // return 5 kthLargest.add(9); // return 8 kthLargest.add(4); // return 8
Example 2:
Input: ["KthLargest", "add", "add", "add", "add"] [[4, [7, 7, 7, 7, 8, 3]], [2], [10], [9], [9]] Output: [null, 7, 7, 7, 8] Explanation: KthLargest kthLargest = new KthLargest(4, [7, 7, 7, 7, 8, 3]); kthLargest.add(2); // return 7 kthLargest.add(10); // return 7 kthLargest.add(9); // return 7 kthLargest.add(9); // return 8
Constraints:
0 <= nums.length <= 1041 <= k <= nums.length + 1-104 <= nums[i] <= 104-104 <= val <= 104- At most
104calls will be made toadd.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
92. Kth Largest Element in an Array (Leetcode:215)#
Also in DSA Patterns
Kth Largest Element in an Array — 15. Heaps (may include extra approaches and complexity analysis).
Problem Statement
Given an integer array nums and an integer k, return the kth largest element in the array.
Note that it is the kth largest element in the sorted order, not the kth distinct element.
Can you solve it without sorting?
Example 1:
Input: nums = [3,2,1,5,6,4], k = 2 Output: 5
Example 2:
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 Output: 4
Constraints:
1 <= k <= nums.length <= 105-104 <= nums[i] <= 104
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
93. Last Stone Weight (Leetcode:1046)#
Also in DSA Patterns
Last Stone Weight — 15. Heaps (may include extra approaches and complexity analysis).
Problem Statement
You are given an array of integers stones where stones[i] is the weight of the ith stone.
We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is:
- If
x == y, both stones are destroyed, and - If
x != y, the stone of weightxis destroyed, and the stone of weightyhas new weighty - x.
At the end of the game, there is at most one stone left.
Return the weight of the last remaining stone. If there are no stones left, return 0.
Example 1:
Input: stones = [2,7,4,1,8,1] Output: 1 Explanation: We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.
Example 2:
Input: stones = [1] Output: 1
Constraints:
1 <= stones.length <= 301 <= stones[i] <= 1000
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
94. 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)
95. Task Scheduler (Leetcode:621)#
Also in DSA Patterns
Task Scheduler — 10. Greedy Algorithm (may include extra approaches and complexity analysis).
Problem Statement
You are given an array of CPU tasks, each labeled with a letter from A to Z, and a number n. Each CPU interval can be idle or allow the completion of one task. Tasks can be completed in any order, but there's a constraint: there has to be a gap of at least n intervals between two tasks with the same label.
Return the minimum number of CPU intervals required to complete all tasks.
Example 1:
Input: tasks = ["A","A","A","B","B","B"], n = 2 Output: 8 Explanation: A possible sequence is: A -> B -> idle -> A -> B -> idle -> A -> B. After completing task A, you must wait two intervals before doing A again. The same applies to task B. In the 3rd interval, neither A nor B can be done, so you idle. By the 4th interval, you can do A again as 2 intervals have passed.
Example 2:
Input: tasks = ["A","C","A","B","D","B"], n = 1 Output: 6 Explanation: A possible sequence is: A -> B -> C -> D -> A -> B. With a cooling interval of 1, you can repeat a task after just one other task.
Example 3:
Input: tasks = ["A","A","A", "B","B","B"], n = 3 Output: 10 Explanation: A possible sequence is: A -> B -> idle -> idle -> A -> B -> idle -> idle -> A -> B. There are only two types of tasks, A and B, which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks.
Constraints:
1 <= tasks.length <= 104tasks[i]is an uppercase English letter.0 <= n <= 100
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
Intervals#
96. 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)
97. 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)
98. 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)
99. 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)
100. Minimum Interval to Include Each Query (Leetcode:1851)#
Also in DSA Patterns
Minimum Interval to Include Each Query — 00. Prefix Sum (may include extra approaches and complexity analysis).
Problem Statement
You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1.
You are also given an integer array queries. The answer to the jth query is the size of the smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer is -1.
Return an array containing the answers to the queries.
Example 1:
Input: intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5] Output: [3,3,1,4] Explanation: The queries are processed as follows: - Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3. - Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3. - Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1. - Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4.
Example 2:
Input: intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22] Output: [2,-1,4,6] Explanation: The queries are processed as follows: - Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2. - Query = 19: None of the intervals contain 19. The answer is -1. - Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4. - Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6.
Constraints:
1 <= intervals.length <= 1051 <= queries.length <= 105intervals[i].length == 21 <= lefti <= righti <= 1071 <= queries[j] <= 107
Code and Explanation
- Build the Prefix Sum Array:
Create a new array prefix where each element at index i stores the sum of elements from the start of the array up to index i:
prefix[0] = arr[0] prefix[1] = arr[0] + arr[1] prefix[2] = arr[0] + arr[1] + arr[2]
And so on…
Example:
For arr = [3, 1, 4, 1, 5, 9], the prefix_sum array is [3, 4, 8, 9, 14, 23]. 2. Answer Range Sum Queries:
To find the sum of elements between indices i and j, use:
sum(i, j) = prefix[j] - prefix[i-1]
Example:
For arr = [3, 1, 4, 1, 5, 9], the sum from index 2 to 4:
sum(2, 4) = prefix[4] - prefix[1] = 14 - 4 = 10. 3. Time: O(n) for building the prefix sum array, O(1) per query. 4. Space: O(n) for storing the prefix sum array. 5. NumArray(int[] nums) Initializes the object with the integer array nums.
101. 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#
102. Add Two Numbers (Leetcode:2)#
Also in DSA Patterns
Add Two Numbers — 07. Linked List (may include extra approaches and complexity analysis).
Problem Statement
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0], l2 = [0] Output: [0]
Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1]
Constraints:
- The number of nodes in each linked list is in the range
[1, 100].0 <= Node.val <= 9- It is guaranteed that the list represents a number that does not have leading zeros.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
103. Copy List with Random Pointer (Leetcode:138)#
Also in DSA Patterns
Copy List with Random Pointer — 07. Linked List (may include extra approaches and complexity analysis).
Problem Statement
A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.
Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.
For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y.
Return the head of the copied linked list.
The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:
val: an integer representingNode.valrandom_index: the index of the node (range from0ton-1) that therandompointer points to, ornullif it does not point to any node.
Your code will only be given the head of the original linked list.
Example 1:
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]] Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
Example 2:
Input: head = [[1,1],[2,1]] Output: [[1,1],[2,1]]
Example 3:
Input: head = [[3,null],[3,0],[3,null]] Output: [[3,null],[3,0],[3,null]]
Constraints:
0 <= n <= 1000-104 <= Node.val <= 104Node.randomisnullor is pointing to some node in the linked list.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
104. 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)
105. 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)
106. 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)
107. 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)
108. 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)
109. Reverse Nodes in k-Group (Leetcode:25)#
Also in DSA Patterns
Reverse Nodes in k-Group — 07. Linked List (may include extra approaches and complexity analysis).
Problem Statement
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4,5], k = 2 Output: [2,1,4,3,5]
Example 2:
Input: head = [1,2,3,4,5], k = 3 Output: [3,2,1,4,5]
Constraints:
- The number of nodes in the list is
n.1 <= k <= n <= 50000 <= Node.val <= 1000
Follow-up: Can you solve the problem in O(1) extra memory space?
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
Math & Geometry#
110. Detect Squares (Leetcode:2013)#
Also in DSA Patterns
Detect Squares — 21. Math and Geometry (may include extra approaches and complexity analysis).
Problem Statement
You are given a stream of points on the X-Y plane. Design an algorithm that:
- Adds new points from the stream into a data structure. Duplicate points are allowed to be added more than once.
- Counts the number of ways to form axis-aligned squares such that the point
(x, y)belongs to the square and has an edge parallel to the X-axis.
Implement the DetectSquares class:
DetectSquares()Initializes the object with an empty data structure.void add(int[] point)Adds a new pointpoint = [x, y]to the data structure.int count(int[] point)Counts the number of ways to form axis-aligned squarespbelongs to.
Example 1:
Input:
["DetectSquares", "add", "add", "add", "count", "count", "add", "count"]
[[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]]
Output:[null, null, null, null, 1, 0, null, 2]
Constraints:
point.length == 2
0 <= x, y <= 1000
At most3000calls toaddandcount.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
111. Multiply Strings (Leetcode:43)#
Problem Statement
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example 1:
Input: num1 = "2", num2 = "3" Output: "6" Example 2:
Input: num1 = "123", num2 = "456" Output: "56088"
Constraints:
1 <= num1.length, num2.length <= 200
num1andnum2consist of digits only.Both
num1andnum2do not contain any leading zero, except the number0itself.
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def multiply(self, num1: str, num2: str) -> str:
if "0" in [num1, num2]:
return "0"
res = [0] * (len(num1) + len(num2))
num1, num2 = num1[::-1], num2[::-1]
for i1 in range(len(num1)):
for i2 in range(len(num2)):
digit = int(num1[i1]) * int(num2[i2])
res[i1 + i2] += digit
res[i1 + i2 + 1] += res[i1 + i2] // 10
res[i1 + i2] = res[i1 + i2] % 10
res, beg = res[::-1], 0
while beg < len(res) and res[beg] == 0:
beg += 1
res = map(str, res[beg:])
return "".join(res)
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
112. Plus One (Leetcode:66)#
Problem Statement
You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
Example 1:
Input: digits = [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123. Incrementing by one gives 123 + 1 = 124. Thus, the result should be [1,2,4].
Example 2:
Input: digits = [4,3,2,1] Output: [4,3,2,2] Explanation: The array represents the integer 4321. Incrementing by one gives 4321 + 1 = 4322. Thus, the result should be [4,3,2,2].
Example 3:
Input: digits = [9] Output: [1,0] Explanation: The array represents the integer 9. Incrementing by one gives 9 + 1 = 10. Thus, the result should be [1,0].
Constraints:
1 <= digits.length <= 100
0 <= digits[i] <= 9
digitsdoes not contain any leading0's.
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
one = 1
i = 0
digits = digits[::-1]
while one:
if i < len(digits):
if digits[i] == 9:
digits[i] = 0
else:
digits[i] += 1
one = 0
else:
digits.append(one)
one = 0
i += 1
return digits[::-1]
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
113. Pow(x n) (Leetcode:50)#
Also in DSA Patterns
Pow(x, n) — 21. Math and Geometry (may include extra approaches and complexity analysis).
Problem Statement
Implement pow(x, n), which calculates x raised to the power n (i.e., x^n).
Example 1:
Input: x = 2.00000, n = 10
Output: 1024.00000
Example 2:
Input: x = 2.10000, n = 3
Output: 9.26100
Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2⁻² = 1/2² = 1/4 = 0.25
Constraints:
-100.0 < x < 100.0
-2^31 <= n <= 2^31 - 1
nis an integer.
Eitherxis not zero orn > 0.
-10^4 <= x^n <= 10^4
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
114. Reverse Integer (Leetcode:7)#
Problem Statement
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123 Output: 321
Example 2:
Input: x = -123 Output: -321
Example 3:
Input: x = 120 Output: 21
Constraints:
-2^31 <= x <= 2^31 - 1
Code and Explanation
- AND (&): Sets a bit to 1 if both corresponding bits are 1.
-
Example: 1101 & 1011 = 1001 (binary) 2. OR (|): Sets a bit to 1 if at least one of the corresponding bits is 1.
-
Example: 1101 | 1011 = 1111 3. XOR (^): Sets a bit to 1 if the corresponding bits are different.
-
Example: 1101 ^ 1011 = 0110 4. NOT (~): Flips all bits (inverts 0s to 1s and 1s to 0s).
-
Example: ~1101 = 0010 (assuming 4-bit representation) 5. Left Shift (<<): Shifts bits to the left, equivalent to multiplying the number by 2.
-
Example: 1010 << 1 = 10100 (multiplies by 2)
Matrix#
115. 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)
116. 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)
117. 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)
118. Valid Sudoku (Leetcode:36)#
Problem Statement
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits
1-9without repetition.Each column must contain the digits
1-9without repetition.Each of the nine
3 x 3sub-boxes of the grid must contain the digits1-9without repetition.
Note:
A Sudoku board (partially filled) could be valid but is not necessarily solvable.
Only the filled cells need to be validated according to the mentioned rules.
Example 1:
Input: board = [["5","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] ,["8",".",".",".","6",".",".",".","3"] ,["4",".",".","8",".","3",".",".","1"] ,["7",".",".",".","2",".",".",".","6"] ,[".","6",".",".",".",".","2","8","."] ,[".",".",".","4","1","9",".",".","5"] ,[".",".",".",".","8",".",".","7","9"]] Output: true
Example 2:
Input: board = [["8","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] ,["8",".",".",".","6",".",".",".","3"] ,["4",".",".","8",".","3",".",".","1"] ,["7",".",".",".","2",".",".",".","6"] ,[".","6",".",".",".",".","2","8","."] ,[".",".",".","4","1","9",".",".","5"] ,[".",".",".",".","8",".",".","7","9"]] Output: false Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
Constraints:
board.length == 9
board[i].length == 9
board[i][j]is a digit1-9or'.'.
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
cols = collections.defaultdict(set)
rows = collections.defaultdict(set)
squares = collections.defaultdict(set) # key = (r /3, c /3)
for r in range(9):
for c in range(9):
if board[r][c] == ".":
continue
if (
board[r][c] in rows[r]
or board[r][c] in cols[c]
or board[r][c] in squares[(r // 3, c // 3)]
):
return False
cols[c].add(board[r][c])
rows[r].add(board[r][c])
squares[(r // 3, c // 3)].add(board[r][c])
return True
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
Sliding Window#
119. 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)
120. 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))
121. 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.
122. Permutation in String (Leetcode:567)#
Also in DSA Patterns
Permutation in String — 03. Sliding Window (may include extra approaches and complexity analysis).
Problem Statement
Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
In other words, return true if one of s1's permutations is the substring of s2.
Example 1:
Input: s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains one permutation of s1 ("ba").
Example 2:
Input: s1 = "ab", s2 = "eidboaoo"
Output: false
Constraints:
1 <= s1.length, s2.length <= 10^4
s1ands2consist of lowercase English letters.
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.
123. Sliding Window Maximum (Leetcode:239)#
Also in DSA Patterns
Sliding Window Maximum — 03. Sliding Window (may include extra approaches and complexity analysis).
Problem Statement
You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window.
Each time the sliding window moves right by one position.
Return the max sliding window.
Example 1:
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7
Example 2:
Input: nums = [1], k = 1
Output: [1]
Constraints:
1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
1 <= k <= nums.length
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#
124. Car Fleet (Leetcode:853)#
Problem Statement
There are n cars at given miles away from the starting mile 0, traveling to reach the mile target.
You are given two integer arrays position and speed, both of length n, where position[i] is the starting mile of the ith car and speed[i] is the speed of the ith car in miles per hour.
A car cannot pass another car, but it can catch up and then travel next to it at the speed of the slower car.
A car fleet is a single car or a group of cars driving next to each other. The speed of the car fleet is the minimum speed of any car in the fleet.
If a car catches up to a car fleet at the mile target, it will still be considered as part of the car fleet.
Return the number of car fleets that will arrive at the destination.
Example 1:
Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
Output: 3
Explanation:
The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The fleet forms at
target.The car starting at 0 (speed 1) does not catch up to any other car, so it is a fleet by itself.
The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches
target.
Example 2:
Input: target = 10, position = [3], speed = [3]
Output: 1
Explanation:
There is only one car, hence there is only one fleet.
Example 3:
Input: target = 100, position = [0,2,4], speed = [4,2,1]
Output: 1
Explanation:
The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The car starting at 4 (speed 1) travels to 5.
Then, the fleet at 4 (speed 2) and the car at position 5 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches
target.
Constraints:
n == position.length == speed.length
1 <= n <= 105
0 < target <= 106
0 <= position[i] < targetAll the values of
positionare unique.
0 < speed[i] <= 106
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
pair = [(p, s) for p, s in zip(position, speed)]
pair.sort(reverse=True)
stack = []
for p, s in pair: # Reverse Sorted Order
stack.append((target - p) / s)
if len(stack) >= 2 and stack[-1] <= stack[-2]:
stack.pop()
return len(stack)
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
125. Daily Temperatures (Leetcode:739)#
Also in DSA Patterns
Daily Temperatures — 08. Stack (may include extra approaches and complexity analysis).
Problem Statement
Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
Example 1:
Input: temperatures = [73,74,75,71,69,72,76,73] Output: [1,1,4,2,1,1,0,0]
Example 2:
Input: temperatures = [30,40,50,60] Output: [1,1,1,0]
Example 3:
Input: temperatures = [30,60,90] Output: [1,1,0]
Constraints:
1 <= temperatures.length <= 10530 <= temperatures[i] <= 100
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
126. Evaluate Reverse Polish Notation (Leetcode:150)#
Also in DSA Patterns
Evaluate Reverse Polish Notation — 08. Stack (may include extra approaches and complexity analysis).
Problem Statement
You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.
Evaluate the expression. Return an integer that represents the value of the expression.
Note that:
- The valid operators are
'+','-','*', and'/'. - Each operand may be an integer or another expression.
- The division between two integers always truncates toward zero.
- There will not be any division by zero.
- The input represents a valid arithmetic expression in a reverse polish notation.
- The answer and all the intermediate calculations can be represented in a 32-bit integer.
Example 1:
Input: tokens = ["2","1","+","3","*"] Output: 9 Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: tokens = ["4","13","5","/","+"] Output: 6 Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: tokens = ["10","6","9","3","+","-11","","/","","17","+","5","+"] Output: 22 Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) + 17) + 5 = ((10 * (6 / -132)) + 17) + 5 = ((10 * 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22
Constraints:
1 <= tokens.length <= 104tokens[i]is either an operator:"+","-","*", or"/", or an integer in the range[-200, 200].
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
127. Largest Rectangle in Histogram (Leetcode:84)#
Also in DSA Patterns
Largest Rectangle in Histogram — 08. Stack (may include extra approaches and complexity analysis).
Problem Statement
Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
Example 1:
Input: heights = [2,1,5,6,2,3] Output: 10 Explanation: The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area, which has an area = 10 units.
Example 2:
Input: heights = [2,4] Output: 4
Constraints:
1 <= heights.length <= 1050 <= heights[i] <= 104
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
128. 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#
129. Balanced Binary Tree (Leetcode:110)#
Also in DSA Patterns
Balanced Binary Tree — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than one.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: true
Example 2:
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
Explanation: The left subtree of node 1 has a depth of 3, while the right subtree has a depth of 1.
Example 3:
Input: root = []
Output: true
Constraints:
- The number of nodes in the tree is in the range
[0, 5000].-10⁴ <= Node.val <= 10⁴
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
130. 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)
131. 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)
132. Binary Tree Right Side View (Leetcode:199)#
Also in DSA Patterns
Binary Tree Right Side View — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
- The number of nodes in the tree is in the range
[0, 100].-100 <= Node.val <= 100
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
133. 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²)
134. Count Good Nodes in Binary Tree (Leetcode:1448)#
Problem Statement
Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
Example 1:
Input: root = [3,1,4,3,null,1,5] Output: 4 Explanation: Nodes in blue are good. Root Node (3) is always a good node. Node 4 -> (3,4) is the maximum value in the path starting from the root. Node 5 -> (3,4,5) is the maximum value in the path Node 3 -> (3,1,3) is the maximum value in the path.
Example 2:
Input: root = [3,3,null,4,2] Output: 3 Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.
Example 3:
Input: root = [1] Output: 1 Explanation: Root is considered as good.
Constraints:
The number of nodes in the binary tree is in the range
[1, 10^5].Each node's value is between
[-10^4, 10^4].
Code and Explanation
=== "Optimal"
```python linenums="1"
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def goodNodes(self, root: TreeNode) -> int:
def dfs(node, maxVal):
if not node:
return 0
res = 1 if node.val >= maxVal else 0
maxVal = max(maxVal, node.val)
res += dfs(node.left, maxVal)
res += dfs(node.right, maxVal)
return res
return dfs(root, root.val)
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
135. Diameter of Binary Tree (Leetcode:543)#
Also in DSA Patterns
Diameter of Binary Tree — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
Given the root of a binary tree, return the length of the diameter — the longest path between any two nodes (path may or may not pass through root).
Example 1:
Input: root = [1,2,3,4,5]
Output: 3
Explanation: Path 4→2→1→3 or 5→2→1→3.
Example 2:
Input: root = [1,2]
Output: 1
Constraints:
1 <= number of nodes <= 10⁴−100 <= Node.val <= 100
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
136. 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)
137. 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)
138. 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)
139. 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)
140. 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)
141. 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)
142. 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#
143. 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)
144. 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)
145. 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#
146. 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)
147. 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)
148. Trapping Rain Water (Leetcode:42)#
Also in DSA Patterns
Trapping Rain Water — 08. Stack (may include extra approaches and complexity analysis).
Problem Statement
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
Example 2:
Input: height = [4,2,0,3,2,5] Output: 9
Constraints:
n == height.length1 <= n <= 2 * 1040 <= height[i] <= 105
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
149. Two Sum II - Input Array Is Sorted (Leetcode:167)#
Problem Statement
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.
Return the indices of the two numbers index1 and index2, each incremented by one, as an integer array [index1, index2] of length 2.
The tests are generated such that there is exactly one solution. You may not use the same element twice.
Your solution must use only constant extra space.
Example 1:
Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
Example 2:
Input: numbers = [2,3,4], target = 6 Output: [1,3] Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
Example 3:
Input: numbers = [-1,0], target = -1 Output: [1,2] Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].
Constraints:
2 <= numbers.length <= 3 * 10^4-1000 <= numbers[i] <= 1000numbersis sorted in non-decreasing order.-1000 <= target <= 1000- The tests are generated such that there is exactly one solution.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
150. 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: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
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: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20
Explanation:
We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.
Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output: 2
Input: points = [[1,3],[-2,2]], k = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]
Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Input: head = [1,2]
Output: [2,1]
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
Input: heights = [2,4]
Output: 4
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: []
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.