LeetCode Top 150#
The LeetCode Top 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. Candy (Leetcode:135)#
Problem Statement
There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
Return the minimum number of candies you need to have to distribute the candies to the children.
Example 1:
Input: ratings = [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: ratings = [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.
Constraints:
n == ratings.length
1 <= n <= 2 * 104
0 <= ratings[i] <= 2 * 104
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def candy(self, ratings: List[int]) -> int:
n = len(ratings)
# Initialize with one candy becuase each child must have at least one candy.
candies = [1] * n
# Iterate from left to right
for i in range(1, n):
# Check if current rating is greater than left neighbor
if ratings[i] > ratings[i - 1]:
# Rating is higher so deserves more candy than left neighbor
candies[i] = candies[i - 1] + 1
# Iterate from right to left
for i in range(n - 2, -1, -1):
# Check if current rating is greater than right neighbor
if ratings[i] > ratings[i + 1]:
# Take max to check if the value is already greater than its right neighbor + 1.
candies[i] = max(candies[i], candies[i + 1] + 1)
return sum(candies)
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
2. Contains Duplicate II (Leetcode:219)#
Problem Statement
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
Example 1:
Input: nums = [1,2,3,1], k = 3 Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1 Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2 Output: false
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
0 <= k <= 105
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
window = set()
L = 0
for R in range(len(nums)):
if R - L > k:
window.remove(nums[L])
L += 1
if nums[R] in window:
return True
window.add(nums[R])
return False
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
3. Find the Index of the First Occurrence in a String (Leetcode:28)#
Also in DSA Patterns
Find the Index of First Occurrence in a String — 20. String Matching (may include extra approaches and complexity analysis).
Problem Statement
Given two strings haystack and needle, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "sadbutsad", needle = "sad" Output: 0
Example 2:
Input: haystack = "leetcode", needle = "leeto" Output: -1
Constraints:
1 <= haystack.length, needle.length <= 10^4, lowercase English letters.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
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. H-Index (Leetcode:274)#
Problem Statement
Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return the researcher's h-index.
According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times.
Example 1:
Input: citations = [3,0,6,1,5] Output: 3 Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.
Example 2:
Input: citations = [1,3,1] Output: 1
Constraints:
n == citations.length
1 <= n <= 5000
0 <= citations[i] <= 1000
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def hIndex(self, citations: List[int]) -> int:
length = len(citations)
citations.sort()
for i in range(length):
if citations[i] >= length - i:
return length - i
return 0
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
7. 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.
8. Integer to Roman (Leetcode:12)#
Problem Statement
Seven different symbols represent Roman numerals with the following values:
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Roman numerals are formed by appending the conversions of decimal place values from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:
If the value does not start with 4 or 9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.
If the value starts with 4 or 9 use the subtractive form representing one symbol subtracted from the following symbol, for example, 4 is 1 (
I) less than 5 (V):IVand 9 is 1 (I) less than 10 (X):IX. Only the following subtractive forms are used: 4 (IV), 9 (IX), 40 (XL), 90 (XC), 400 (CD) and 900 (CM).Only powers of 10 (
I,X,C,M) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5 (V), 50 (L), or 500 (D) multiple times. If you need to append a symbol 4 times use the subtractive form.
Given an integer, convert it to a Roman numeral.
Example 1:
Input: num = 3749
Output: "MMMDCCXLIX"
Explanation:
3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M) 700 = DCC as 500 (D) + 100 (C) + 100 (C) 40 = XL as 10 (X) less of 50 (L) 9 = IX as 1 (I) less of 10 (X) Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places
Example 2:
Input: num = 58
Output: "LVIII"
Explanation:
50 = L 8 = VIII
Example 3:
Input: num = 1994
Output: "MCMXCIV"
Explanation:
1000 = M 900 = CM 90 = XC 4 = IV
Constraints:
1 <= num <= 3999
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def intToRoman(self, num: int) -> str:
symList = [
["I", 1],
["IV", 4],
["V", 5],
["IX", 9],
["X", 10],
["XL", 40],
["L", 50],
["XC", 90],
["C", 100],
["CD", 400],
["D", 500],
["CM", 900],
["M", 1000],
]
res = ""
for sym, val in reversed(symList):
if num // val:
count = num // val
res += sym * count
num = num % val
return res
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
9. Isomorphic Strings (Leetcode:205)#
Problem Statement
Given two strings s and t, determine if they are isomorphic.
Two strings s and t are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.
Example 1:
Input: s = "egg", t = "add"
Output: true
Explanation:
The strings s and t can be made identical by:
Mapping
'e'to'a'.Mapping
'g'to'd'.
Example 2:
Input: s = "f11", t = "b23"
Output: false
Explanation:
The strings s and t can not be made identical as '1' needs to be mapped to both '2' and '3'.
Example 3:
Input: s = "paper", t = "title"
Output: true
Constraints:
1 <= s.length <= 5 * 104
t.length == s.length
sandtconsist of any valid ascii character.
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
mapST, mapTS = {}, {}
for c1, c2 in zip(s, t):
if (c1 in mapST and mapST[c1] != c2) or (c2 in mapTS and mapTS[c2] != c1):
return False
mapST[c1] = c2
mapTS[c2] = c1
return True
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
10. 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)
11. 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.
12. Length of Last Word (Leetcode:58)#
Problem Statement
Given a string s consisting of words and spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = "Hello World" Output: 5 Explanation: The last word is "World" with length 5.
Example 2:
Input: s = " fly me to the moon " Output: 4 Explanation: The last word is "moon" with length 4.
Example 3:
Input: s = "luffy is still joyboy" Output: 6 Explanation: The last word is "joyboy" with length 6.
Constraints:
1 <= s.length <= 104
sconsists of only English letters and spaces' '.There will be at least one word in
s.
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def lengthOfLastWord(self, s: str) -> int:
"""
one shortcut
"""
# return len(s.split()[-1])
count = 0
for i in range(len(s) - 1, -1, -1):
char = s[i]
if char == " ":
if count >= 1:
return count
else:
count += 1
return count
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
13. Longest Common Prefix (Leetcode:14)#
Problem Statement
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"] Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]consists of only lowercase English letters if it is non-empty.
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
for i in range(len(strs[0])):
for s in strs:
if i >= len(s) or s[i] != strs[0][i]:
return strs[0][:i]
return strs[0]
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
14. 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)
15. Majority Element (Leetcode:169)#
Problem Statement
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
Example 1:
Input: nums = [3,2,3] Output: 3 Example 2:
Input: nums = [2,2,1,1,1,2,2] Output: 2
Constraints:
n == nums.length
1 <= n <= 5 * 104
-109 <= nums[i] <= 109The input is generated such that a majority element will exist in the array.
Follow-up: Could you solve the problem in linear time and in O(1) space?
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def majorityElement(self, nums: List[int]) -> int:
res, count = 0, 0
for n in nums:
if count == 0:
res = n
count += (1 if n == res else -1)
return res
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
16. Merge Sorted Array (Leetcode:88)#
Problem Statement
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
Example 1:
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
Example 2:
Input: nums1 = [1], m = 1, nums2 = [], n = 0 Output: [1] Explanation: The arrays we are merging are [1] and []. The result of the merge is [1].
Example 3:
Input: nums1 = [0], m = 0, nums2 = [1], n = 1 Output: [1] Explanation: The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
Constraints:
nums1.length == m + n
nums2.length == n
0 <= m, n <= 200
1 <= m + n <= 200
-109 <= nums1[i], nums2[j] <= 109
Follow up: Can you come up with an algorithm that runs in O(m + n) time?
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
while m > 0 and n > 0:
if nums1[m-1] >= nums2[n-1]:
nums1[m+n-1] = nums1[m-1]
m -= 1
else:
nums1[m+n-1] = nums2[n-1]
n -= 1
if n > 0:
nums1[:n] = nums2[:n]
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
17. 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)
18. Ransom Note (Leetcode:383)#
Problem Statement
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.
Example 1:
Input: ransomNote = "a", magazine = "b" Output: false Example 2:
Input: ransomNote = "aa", magazine = "ab" Output: false Example 3:
Input: ransomNote = "aa", magazine = "aab" Output: true
Constraints:
1 <= ransomNote.length, magazine.length <= 105
ransomNoteandmagazineconsist of lowercase English letters.
Code and Explanation
=== "Optimal"
```python linenums="1"
from collections import Counter
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
r_counter = Counter(ransomNote)
m_counter = Counter(magazine)
# magazine contains (>=) ransomNote
for c in ransomNote:
if m_counter[c] < r_counter[c]:
return False
return True
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
19. Remove Duplicates from Sorted Array (Leetcode:26)#
Also in DSA Patterns
Remove Duplicates from Sorted Array — 01. Two Pointers (may include extra approaches and complexity analysis).
Problem Statement
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.
Return k after placing the final result in the first k slots of nums.
Example 1:
Input: nums = [1,1,2] Output: 2, nums = [1,2,_]
Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4] Output: 5, nums = [0,1,2,3,4,,,,,_]
Constraints:
1 <= nums.length <= 3 * 10^4-10^4 <= nums[i] <= 10^4numsis sorted in non-decreasing order.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
20. Remove Duplicates from Sorted Array II (Leetcode:80)#
Problem Statement
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of nums.
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums[i] == expectedNums[i]; }
If all assertions pass, then your solution will be accepted.
Example 1:
Input: nums = [1,1,1,2,2,3] Output: 5, nums = [1,1,2,2,3,_] Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,0,1,1,1,1,2,3,3] Output: 7, nums = [0,0,1,1,2,3,3,,] Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints:
1 <= nums.length <= 3 * 104
-104 <= nums[i] <= 104
numsis sorted in non-decreasing order.
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
l, r = 0, 0
while r < len(nums):
count = 1
while r + 1 < len(nums) and nums[r] == nums[r + 1]:
r += 1
count += 1
for i in range(min(2, count)):
nums[l] = nums[r]
l += 1
r += 1
return l
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
21. Remove Element (Leetcode:27)#
Problem Statement
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
Change the array
numssuch that the firstkelements ofnumscontain the elements which are not equal toval. The remaining elements ofnumsare not important as well as the size ofnums.Return
k.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val.
int k = removeElement(nums, val); // Calls your implementation
assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i < actualLength; i++) { assert nums[i] == expectedNums[i]; }
If all assertions pass, then your solution will be accepted.
Example 1:
Input: nums = [3,2,2,3], val = 3 Output: 2, nums = [2,2,,] Explanation: Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,1,2,2,3,0,4,2], val = 2 Output: 5, nums = [0,1,4,0,3,,,_] Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints:
0 <= nums.length <= 100
0 <= nums[i] <= 50
0 <= val <= 100
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
k = 0
for i in range(len(nums)):
if nums[i] != val:
nums[k] = nums[i]
k += 1
return k
# Optimized solution with the same time and space complexity
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
# Avoid unessary copy operations in a previous solution, when k == i and nums[i] != val
# by swapping nums[i] and the last element of the array (nums[n])
n = len(nums)
i = 0
while i < n:
if nums[i] == val:
nums[i], nums[n - 1] = nums[n - 1], nums[i]
n -= 1 # decrement the length of the array by discarding the last element
else:
i += 1
return n
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
22. Reverse Words in a String (Leetcode:151)#
Also in DSA Patterns
Reverse Words in a String — 01. Two Pointers (may include extra approaches and complexity analysis).
Problem Statement
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Example 1:
Input: s = "the sky is blue" Output: "blue is sky the"
Example 2:
Input: s = " hello world " Output: "world hello" Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: s = "a good example" Output: "example good a" Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
Constraints:
1 <= s.length <= 10^4scontains English letters, digits, and spaces. There is at least one word ins.
Code and Explanation
- This technique is ideal for problems like finding unique elements, counting subarrays, or rearranging elements.
- One pointer (typically called slow) moves through the array, while the other pointer (called fast) explores further elements.
- The slow pointer often keeps track of the current valid position, while the fast pointer scans for new valid elements.
- This is especially useful for sliding window problems, where the window expands and shrinks by adjusting the pointers.
- It can also be used to remove duplicates in-place in an array.
23. Roman to Integer (Leetcode:13)#
Problem Statement
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
Ican be placed beforeV(5) andX(10) to make 4 and 9.
Xcan be placed beforeL(50) andC(100) to make 40 and 90.
Ccan be placed beforeD(500) andM(1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
Example 1:
Input: s = "III" Output: 3 Explanation: III = 3.
Example 2:
Input: s = "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3.
Example 3:
Input: s = "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:
1 <= s.length <= 15
scontains only the characters('I', 'V', 'X', 'L', 'C', 'D', 'M').It is guaranteed that
sis a valid roman numeral in the range[1, 3999].
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def romanToInt(self, s: str) -> int:
roman = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
res = 0
for i in range(len(s)):
if i + 1 < len(s) and roman[s[i]] < roman[s[i + 1]]:
res -= roman[s[i]]
else:
res += roman[s[i]]
return res
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
24. Rotate Array (Leetcode:189)#
Problem Statement
Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: nums = [-1,-100,3,99], k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100]
Constraints:
1 <= nums.length <= 10^5-2^31 <= nums[i] <= 2^31 - 10 <= k <= 10^5
Follow up:
- Try to come up with as many solutions as you can. There are at least three different approaches. Solve it in-place with O(1) extra space.
Code and Explanation
- This technique is ideal for problems like finding unique elements, counting subarrays, or rearranging elements.
- One pointer (typically called slow) moves through the array, while the other pointer (called fast) explores further elements.
- The slow pointer often keeps track of the current valid position, while the fast pointer scans for new valid elements.
- This is especially useful for sliding window problems, where the window expands and shrinks by adjusting the pointers.
- It can also be used to remove duplicates in-place in an array.
25. Text Justification (Leetcode:68)#
Problem Statement
Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left-justified, and no extra space is inserted between words.
Note:
A word is defined as a character sequence consisting of non-space characters only.
Each word's length is guaranteed to be greater than
0and not exceedmaxWidth.The input array
wordscontains at least one word.
Example 1:
Input: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16 Output: [ "This is an", "example of text", "justification. " ]
Example 2:
Input: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16 Output: [ "What must be", "acknowledgment ", "shall be " ] Explanation: Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified. Note that the second line is also left-justified because it contains only one word.
Example 3:
Input: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20 Output: [ "Science is what we", "understand well", "enough to explain to", "a computer. Art is", "everything else we", "do " ]
Constraints:
1 <= words.length <= 300
1 <= words[i].length <= 20
words[i]consists of only English letters and symbols.
1 <= maxWidth <= 100
words[i].length <= maxWidth
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
res = []
line = [] # Words in current line
length = 0 # Current line length
i = 0
while i < len(words):
if length + len(line) + len(words[i]) > maxWidth:
# Line complete
extra_space = maxWidth - length
word_cnt = len(line) - 1
spaces = extra_space // max(1, word_cnt)
remainder = extra_space % max(1, word_cnt)
for j in range(max(1, len(line) - 1)):
line[j] += " " * spaces
if remainder:
line[j] += " "
remainder -= 1
res.append("".join(line))
line, length = [], 0 # Reset line and length
line.append(words[i])
length += len(words[i])
i += 1
# Handling the last line
last_line = " ".join(line)
trail_spaces = maxWidth - len(last_line)
res.append(last_line + (trail_spaces * " "))
return res
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
26. 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)
27. 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)
28. Word Pattern (Leetcode:290)#
Problem Statement
Given a pattern and a string s, find if s follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s. Specifically:
Each letter in
patternmaps to exactly one unique word ins.Each unique word in
smaps to exactly one letter inpattern.No two letters map to the same word, and no two words map to the same letter.
Example 1:
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Explanation:
The bijection can be established as:
'a'maps to"dog".
'b'maps to"cat".
Example 2:
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false
Constraints:
1 <= pattern.length <= 300
patterncontains only lower-case English letters.
1 <= s.length <= 3000
scontains only lowercase English letters and spaces' '.
sdoes not contain any leading or trailing spaces.All the words in
sare separated by a single space.
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split(" ")
if len(pattern) != len(words):
return False
charToWord = {}
wordToChar = {}
for c, w in zip(pattern, words):
if c in charToWord and charToWord[c] != w:
return False
if w in wordToChar and wordToChar[w] != c:
return False
charToWord[c] = w
wordToChar[w] = c
return True
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
29. Zigzag Conversion (Leetcode:6)#
Problem Statement
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N A P L S I I G Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I
Example 3:
Input: s = "A", numRows = 1 Output: "A"
Constraints:
1 <= s.length <= 1000
sconsists of English letters (lower-case and upper-case),','and'.'.
1 <= numRows <= 1000
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1 or numRows >= len(s):
return s
res = [""] * numRows
index = 0
step = 1
for c in s:
res[index] += c
if index == 0:
step = 1
elif index == numRows - 1:
step = -1
index += step
return "".join(res)
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
Backtracking#
30. 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)
31. Combinations (Leetcode:77)#
Also in DSA Patterns
Combinations — 12. Backtracking (may include extra approaches and complexity analysis).
Problem Statement
Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].
You may return the answer in any order.
Example 1:
Input: n = 4, k = 2 Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] Explanation: There are 4 choose 2 = 6 total combinations. Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.
Example 2:
Input: n = 1, k = 1 Output: [[1]] Explanation: There is 1 choose 1 = 1 total combination.
Constraints:
1 <= n <= 201 <= k <= n
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
32. 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.
33. 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.
34. N-Queens II (Leetcode:52)#
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 the number of distinct solutions to the n-queens puzzle**.
Example 1:
Input: n = 4 Output: 2 Explanation: There are two distinct solutions to the 4-queens puzzle as shown.
Example 2:
Input: n = 1 Output: 1
Constraints:
1 <= n <= 9
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def totalNQueens(self, n: int) -> int:
answer = 0
cols = set()
posdiag = set()
negdiag = set()
def backtrack(i):
if i == n:
nonlocal answer
answer += 1
return
for j in range(n):
if j in cols or (i+j) in posdiag or (i-j) in negdiag:
continue
cols.add(j)
posdiag.add(i+j)
negdiag.add(i-j)
backtrack(i+1)
cols.remove(j)
posdiag.remove(i+j)
negdiag.remove(i-j)
backtrack(0)
return answer
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
35. 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.
36. 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#
37. Find First and Last Position of Element in Sorted Array (Leetcode:34)#
Also in DSA Patterns
Find First and Last Position of Element in Sorted Array — 09. Binary Search (may include extra approaches and complexity analysis).
Problem Statement
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1]
Example 3:
Input: nums = [], target = 0 Output: [-1,-1]
Constraints:
0 <= nums.length <= 105-109 <= nums[i] <= 109numsis a non-decreasing array.-109 <= target <= 109
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
38. 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)
39. Find Peak Element (Leetcode:162)#
Also in DSA Patterns
Find Peak Element — 09. Binary Search (may include extra approaches and complexity analysis).
Problem Statement
A peak element is an element that is strictly greater than its neighbors.
Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.
You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in O(log n) time.
Example 1:
Input: nums = [1,2,3,1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
Input: nums = [1,2,1,3,5,6,4] Output: 5 Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
Constraints:
1 <= nums.length <= 1000-231 <= nums[i] <= 231 - 1nums[i] != nums[i + 1]for all validi.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
40. 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.
41. 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.
42. 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)
43. Search Insert Position (Leetcode:35)#
Also in DSA Patterns
Search Insert Position — 09. Binary Search (may include extra approaches and complexity analysis).
Problem Statement
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [1,3,5,6], target = 5 Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2 Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7 Output: 4
Constraints:
1 <= nums.length <= 104-104 <= nums[i] <= 104numscontains distinct values sorted in ascending order.-104 <= target <= 104
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
Bit Manipulation#
44. Add Binary (Leetcode:67)#
Problem Statement
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1" Output: "100" Example 2:
Input: a = "1010", b = "1011" Output: "10101"
Constraints:
1 <= a.length, b.length <= 104
aandbconsist only of'0'or'1'characters.Each string does not contain leading zeros except for the zero itself.
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def addBinary(self, a: str, b: str) -> str:
res = ""
carry = 0
a, b = a[::-1], b[::-1]
for i in range(max(len(a), len(b))):
bitA = ord(a[i]) - ord('0') if i < len(a) else 0
bitB = ord(b[i]) - ord('0') if i < len(b) else 0
total = bitA + bitB + carry
char = str(total % 2)
res = char + res
carry = total // 2
if carry:
res = "1" + res
return res
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
45. Bitwise AND of Numbers Range (Leetcode:201)#
Also in DSA Patterns
Bitwise AND of Numbers Range — 06. Bit Manipulation (may include extra approaches and complexity analysis).
Problem Statement
Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: left = 5, right = 7
Output: 4
Example 2:
Input: left = 0, right = 0
Output: 0
Example 3:
Input: left = 1, right = 2147483647
Output: 0
Constraints:
0 <= left <= right <= 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)
46. 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)
47. 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)
48. 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.
49. Single Number II (Leetcode:137)#
Problem Statement
Given an integer array nums where every element appears three times except for one, which appears exactly once, find the single element.
Example 1:
Input: nums = [2,2,3,2] Output: 3
Constraints:
- 1 <= nums.length <= 3 * 10^4
- -2^31 <= nums[i] <= 2^31 - 1
Code and Explanation
- Use two bitmasks to count each bit modulo 3.
- ones tracks bits seen once; twos tracks bits seen twice.
- After processing, ones holds the bits of the unique number.
Design#
50. 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)
51. Insert Delete GetRandom O(1) (Leetcode:380)#
Also in DSA Patterns
Insert Delete GetRandom O(1) — 22. Challenge Yourself (may include extra approaches and complexity analysis).
Problem Statement
Implement the RandomizedSet class:
RandomizedSet()Initializes theRandomizedSetobject.bool insert(int val)Inserts an itemvalinto the set if not present. Returnstrueif the item was not present,falseotherwise.bool remove(int val)Removes an itemvalfrom the set if present. Returnstrueif the item was present,falseotherwise.int getRandom()Returns a random element from the current set. Each element must have the same probability of being returned.
You must implement the functions of the class such that each function works in average O(1) time complexity.
Example 1:
Input: ["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
Output: [null, true, false, true, 2, true, false, 2]
Constraints:
-231 <= val <= 231 - 1- At most
2 * 105calls will be made toinsert,remove, andgetRandom.- There will be at least one element in the structure when
getRandomis called.
Patterns: Hash Map · Array
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
52. 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.
53. 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.
Divide & Conquer#
54. Construct Quad Tree (Leetcode:427)#
Problem Statement
Given an n x n matrix grid where n is a power of 2, construct a quad tree representing the grid.
Example 1:
Input: grid = [[0,1],[1,0]] Output: [[0,1],[1,0],[1,1],[1,1],[1,0]]
Constraints:
- n == grid.length == grid[i].length
- n == 2^x where 0 <= x <= 6
Code and Explanation
- If a subgrid is uniform, create a leaf node with that value.
- Otherwise split the region into four equal quadrants recursively.
- Return an internal node with isLeaf=False and four children.
55. Convert Sorted Array to Binary Search Tree (Leetcode:108)#
Also in DSA Patterns
Convert Sorted Array to Binary Search Tree — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
Example 1:
Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation:
[0,-10,5,null,-3,null,9] is also accepted:
![]()
Example 2:
Input: nums = [1,3]
Output: [3,1]
Explanation:
[1,null,3] and [3,1] are both height-balanced BSTs.
Constraints:
1 4-104 4numsis sorted in a strictly increasing order.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
56. Sort List (Leetcode:148)#
Problem Statement
Given the head of a linked list, return the list after sorting it in ascending order**.
Example 1:
Input: head = [4,2,1,3] Output: [1,2,3,4]
Example 2:
Input: head = [-1,5,3,4,0] Output: [-1,0,3,4,5]
Example 3:
Input: head = [] Output: []
Constraints:
The number of nodes in the list is in the range
[0, 5 * 104].
-105 <= Node.val <= 105
Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
mid = self.get_mid(head)
left, right = self.sortList(head), self.sortList(mid)
return self.merge_two_sorted(left, right)
def merge_two_sorted(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if not list1:
return list2
if not list2:
return list1
sentinel = ListNode()
prev = sentinel
while list1 and list2:
if list1.val < list2.val:
prev.next = list1
list1 = list1.next
else:
prev.next = list2
list2 = list2.next
prev = prev.next
if list1:
prev.next = list1
else:
prev.next = list2
return sentinel.next
def get_mid(self, head: Optional[ListNode]) -> Optional[ListNode]:
mid_prev = None
while head and head.next:
mid_prev = mid_prev.next if mid_prev else head
head = head.next.next
mid = mid_prev.next
mid_prev.next = None
return mid
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
Dynamic Programming#
57. 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)
58. Best Time to Buy and Sell Stock II (Leetcode:122)#
Also in DSA Patterns
Best Time to Buy and Sell Stock II — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
Given prices, you may complete as many transactions as you like (buy one and sell one share multiple times). You may not hold more than one share at a time. Return the maximum profit.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: (1,5)+(3,6) = 4+3 = 7.
Example 2:
Input: prices = [1,2,3,4,5]
Output: 4
Constraints:
1 <= prices.length <= 3 × 10⁴0 <= prices[i] <= 10⁴
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
59. Best Time to Buy and Sell Stock III (Leetcode:123)#
Also in DSA Patterns
Best Time to Buy and Sell Stock III — 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. Find the maximum profit you can achieve with at most two transactions.
Example 1:
Input: prices = [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0), sell on day 6 (price = 3), buy on day 7 (price = 1), sell on day 8 (price = 4).
Constraints:
- 1 <= prices.length <= 10^5
- 0 <= prices[i] <= 10^5
Code and Explanation
- Track the best cost for the first buy and profit after the first sell.
- Extend to a second transaction using profit from the first sell.
- sell2 holds the maximum profit achievable with at most two transactions.
60. Best Time to Buy and Sell Stock IV (Leetcode:188)#
Also in DSA Patterns
Best Time to Buy and Sell Stock IV — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k. Find the maximum profit you can achieve with at most k transactions.
Example 1:
Input: k = 2, prices = [2,4,1] Output: 2 Explanation: Buy on day 3 (price = 1) and sell on day 2 (price = 4), profit = 3 - 1 = 2.
Constraints:
- 1 <= k <= 100
- 1 <= prices.length <= 1000
- 0 <= prices[i] <= 1000
Code and Explanation
- If k is large enough, unlimited-transaction greedy applies.
- Otherwise use DP arrays buy[j] and sell[j] for j transactions.
- Update sell before buy for each price to avoid same-day reuse.
61. 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)
62. 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)
63. 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.
64. 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)
65. 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.
66. 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)
67. 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²)
68. Maximal Square (Leetcode:221)#
Also in DSA Patterns
Maximal Square — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
Given an m × n binary matrix matrix filled with 0s and 1s, find the largest square containing only 1s and return its area.
Example 1:
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 4
Example 2:
Input: matrix = [["0","1"],["1","0"]]
Output: 1
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 300matrix[i][j]is'0'or'1'.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
69. 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)
70. Maximum Sum Circular Subarray (Leetcode:918)#
Problem Statement
Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.
A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n].
A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j], there does not exist i <= k1, k2 <= j with k1 % n == k2 % n.
Example 1:
Input: nums = [1,-2,3,-2] Output: 3 Explanation: Subarray [3] has maximum sum 3.
Example 2:
Input: nums = [5,-3,5] Output: 10 Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10.
Example 3:
Input: nums = [-3,-2,-3] Output: -2 Explanation: Subarray [-2] has maximum sum -2.
Constraints:
n == nums.length
1 <= n <= 3 * 104
-3 * 104 <= nums[i] <= 3 * 104
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def maxSubarraySumCircular(self, nums: List[int]) -> int:
globMax, globMin = nums[0], nums[0]
curMax, curMin = 0, 0
total = 0
for i, n in enumerate(nums):
curMax = max(curMax + n, n)
curMin = min(curMin + n, n)
total += n
globMax = max(curMax, globMax)
globMin = min(curMin, globMin)
return max(globMax, total - globMin) if globMax > 0 else globMax
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
71. Minimum Path Sum (Leetcode:64)#
Also in DSA Patterns
Minimum Path Sum in Grid — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
Given an m × n grid filled with non-negative numbers, find a path from top-left to bottom-right which minimizes the sum of all numbers along its path. You may only move down or right.
Example 1:
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Path 1→3→1→1→1 sums to 7.
Example 2:
Input: grid = [[1,2,3],[4,5,6]]
Output: 12
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 2000 <= grid[i][j] <= 200
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
72. Triangle (Leetcode:120)#
Also in DSA Patterns
Triangle — 13. Dynamic Programming (may include extra approaches and complexity analysis).
Problem Statement
Given a triangle array triangle, return the minimum path sum from top to bottom. Each step you may move to an adjacent number on the row below. Adjacent for index j on row i means indices j or j+1 on row i+1.
Example 1:
Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output: 11
Explanation: 2 + 3 + 5 + 1 = 11.
Example 2:
Input: triangle = [[-10]]
Output: -10
Constraints:
1 <= triangle.length <= 200triangle[0].length == 1triangle[i].length == triangle[i - 1].length + 1−10⁴ <= triangle[i][j] <= 10⁴
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
73. Unique Paths II (Leetcode:63)#
Problem Statement
You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.
An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle.
Return the number of possible unique paths that the robot can take to reach the bottom-right corner.
The testcases are generated so that the answer will be less than or equal to 2 * 109.
Example 1:
Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]] Output: 2 Explanation: There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right
Example 2:
Input: obstacleGrid = [[0,1],[0,0]] Output: 1
Constraints:
m == obstacleGrid.length
n == obstacleGrid[i].length
1 <= m, n <= 100
obstacleGrid[i][j]is0or1.
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def uniquePathsWithObstacles(self, grid: List[List[int]]) -> int:
M, N = len(grid), len(grid[0])
dp = [0] * N
dp[N-1] = 1
# Time: O(N*M), Space: O(N)
for r in reversed(range(M)):
for c in reversed(range(N)):
if grid[r][c]:
dp[c] = 0
elif c + 1 < N:
dp[c] = dp[c] + dp[c + 1]
return dp[0]
# Time: O(N*M), Space: O(N*M)
M, N = len(grid), len(grid[0])
dp = {(M - 1, N - 1): 1}
def dfs(r, c):
if r == M or c == N or grid[r][c]:
return 0
if (r, c) in dp:
return dp[(r, c)]
dp[(r, c)] = dfs(r + 1, c) + dfs(r, c + 1)
return dp[(r, c)]
return dfs(0, 0)
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
74. 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#
75. 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)
76. 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)
77. 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.
78. Evaluate Division (Leetcode:399)#
Problem Statement
You are given equations, values, and queries representing division relations. Return the answers to all queries. If an answer cannot be determined, return -1.0.
Example 1:
Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]] Output: [6.0,0.5,-1.0,1.0,-1.0]
Constraints:
- 1 <= equations.length <= 20
Code and Explanation
- Build a weighted directed graph for each division relation.
- For each query, DFS from numerator to denominator multiplying edge weights.
- Return -1.0 when either variable is unknown or no path exists.
79. Minimum Genetic Mutation (Leetcode:433)#
Problem Statement
A gene string can be transformed by changing one letter at a time. Given startGene, endGene, and bank, return the minimum number of mutations needed to change startGene into endGene. Return -1 if it is impossible.
Example 1:
Input: startGene = "AACCGGTT", endGene = "AACCGGTA", bank = ["AACCGGTA"] Output: 1
Constraints:
- 1 <= bank.length <= 10
- All gene strings have length 8.
Code and Explanation
- Treat valid bank genes as nodes in an unweighted graph.
- BFS from startGene, generating one-letter neighbors at each step.
- Return the first time endGene is reached, or -1 if unreachable.
80. 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)
81. Snakes and Ladders (Leetcode:909)#
Problem Statement
You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row.
You start on square 1 of the board. In each move, starting from square curr, do the following:
Choose a destination square
nextwith a label in the range[curr + 1, min(curr + 6, n2)].This choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board.
If
nexthas a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move tonext.The game ends when you reach the square
n2.
A board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination of that snake or ladder is board[r][c]. Squares 1 and n2 are not the starting points of any snake or ladder.
Note that you only take a snake or ladder at most once per dice roll. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder.
- For example, suppose the board is
[[-1,4],[-1,3]], and on the first move, your destination square is2. You follow the ladder to square3, but do not follow the subsequent ladder to4.
Return the least number of dice rolls required to reach the square n2. If it is not possible to reach the square, return -1.
Example 1:
Input: board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]] Output: 4 Explanation: In the beginning, you start at square 1 (at row 5, column 0). You decide to move to square 2 and must take the ladder to square 15. You then decide to move to square 17 and must take the snake to square 13. You then decide to move to square 14 and must take the ladder to square 35. You then decide to move to square 36, ending the game. This is the lowest possible number of moves to reach the last square, so return 4.
Example 2:
Input: board = [[-1,-1],[-1,3]] Output: 1
Constraints:
n == board.length == board[i].length
2 <= n <= 20
board[i][j]is either-1or in the range[1, n2].The squares labeled
1andn2are not the starting points of any snake or ladder.
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def snakesAndLadders(self, board: List[List[int]]) -> int:
length = len(board)
board.reverse()
def intToPos(square):
r = (square - 1) // length
c = (square - 1) % length
if r % 2:
c = length - 1 - c
return [r, c]
q = deque()
q.append([1, 0]) # [square, moves]
visit = set()
while q:
square, moves = q.popleft()
for i in range(1, 7):
nextSquare = square + i
r, c = intToPos(nextSquare)
if board[r][c] != -1:
nextSquare = board[r][c]
if nextSquare == length * length:
return moves + 1
if nextSquare not in visit:
visit.add(nextSquare)
q.append([nextSquare, moves + 1])
return -1
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. 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. 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.
Heap / Priority Queue#
84. Find K Pairs with Smallest Sums (Leetcode:373)#
Also in DSA Patterns
Find K Pairs with Smallest Sums — 14. K-way Merge (may include extra approaches and complexity analysis).
Problem Statement
You are given two integer arrays nums1 and nums2 sorted in non-decreasing order and an integer k.
Define a pair (u, v) which consists of one element from the first array and one element from the second array.
Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.
Example 1:
Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3 Output: [[1,2],[1,4],[1,6]] Explanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
Example 2:
Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2 Output: [[1,1],[1,1]] Explanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
Constraints:
1 <= nums1.length, nums2.length <= 105-109 <= nums1[i], nums2[i] <= 109nums1andnums2both are sorted in non-decreasing order.1 <= k <= 104k <= nums1.length * nums2.length
Code and Explanation
- Seed a min-heap with pairs (nums1[i], nums2[0]) for the first k indices.
- Pop the smallest sum and push the next pair from the same nums1 row.
- Stop after collecting k pairs.
85. IPO (Leetcode:502)#
Also in DSA Patterns
IPO — 10. Greedy Algorithm (may include extra approaches and complexity analysis).
Problem Statement
Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects.
You are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it.
Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.
Pick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital.
The answer is guaranteed to fit in a 32-bit signed integer.
Example 1:
Input: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1] Output: 4 Explanation: Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.
Example 2:
Input: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2] Output: 6
Constraints:
1 <= k <= 1050 <= w <= 109n == profits.lengthn == capital.length1 <= n <= 1050 <= profits[i] <= 1040 <= capital[i] <= 109
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
86. 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.
87. Merge k Sorted Lists (Leetcode:23)#
Also in DSA Patterns
Merge k Sorted Lists — 07. Linked List (may include extra approaches and complexity analysis).
Problem Statement
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted linked list: 1->1->2->3->4->4->5->6
Example 2:
Input: lists = [] Output: []
Example 3:
Input: lists = [[]] Output: []
Constraints:
k == lists.length0 <= k <= 1040 <= lists[i].length <= 500-104 <= lists[i][j] <= 104lists[i]is sorted in ascending order.- The sum of
lists[i].lengthwill not exceed104.
Code and Explanation
- Push head of each list onto min-heap.
- Pop smallest, append to result, push that node's next.
- O(N log k) for total N nodes across k lists.
- Time complexity: O(N log k)
- Space complexity: O(k)
- Repeatedly merge pairs of lists until one remains.
- merge_two standard sorted merge.
- O(N log k) without heap.
- Time complexity: O(N log k)
- Space complexity: O(1)
Intervals#
88. 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)
89. 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)
90. Minimum Number of Arrows to Burst Balloons (Leetcode:452)#
Also in DSA Patterns
Minimum Number of Arrows to Burst Balloons — 00. Prefix Sum (may include extra approaches and complexity analysis).
Problem Statement
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.
Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
Given the array points, return the minimum number of arrows that must be shot to burst all balloons.
Example 1:
Input: points = [[10,16],[2,8],[1,6],[7,12]] Output: 2 Explanation: The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. - Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].
Example 2:
Input: points = [[1,2],[3,4],[5,6],[7,8]] Output: 4 Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows.
Example 3:
Input: points = [[1,2],[2,3],[3,4],[4,5]] Output: 2 Explanation: The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. - Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].
Constraints:
1 <= points.length <= 105points[i].length == 2-231 <= xstart < xend <= 231 - 1
Code and Explanation
- Non-overlapping (Separate):
-
Condition: \(a_2 < b_1\) or \(b_2 < a_1\) 2. Description: The intervals do not overlap and are entirely separate. No merging is needed. 3. Partial Overlap (b ends after a):
-
Condition: \(a_1 \leq b_1 \leq a_2 \leq b_2\) 4. Description: The interval \(b\) partially overlaps \(a\), extending beyond it. In this case, \(b\)'s end is after \(a\)'s end. 5. Complete Overlap (a contains b):
-
Condition: \(a_1 \leq b_1 \leq b_2 \leq a_2\)
91. Summary Ranges (Leetcode:228)#
Problem Statement
You are given a sorted unique integer array nums. Return the smallest sorted list of ranges that cover all numbers in the array exactly.
Example 1:
Input: nums = [0,1,2,4,5,7] Output: ["0->2","4->5","7"]
Constraints:
- 0 <= nums.length <= 20
- -2^31 <= nums[i] <= 2^31 - 1
Code and Explanation
- Scan the sorted array and mark the start of each range.
- Extend the range while the next number is consecutive.
- Format single values or start->end pairs and move on.
Linked List#
92. 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.
93. 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.
94. 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)
95. 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)
96. Partition List (Leetcode:86)#
Also in DSA Patterns
Partition List — 07. Linked List (may include extra approaches and complexity analysis).
Problem Statement
Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example 1:
Input: head = [1,4,3,2,5,2], x = 3 Output: [1,2,2,4,3,5]
Example 2:
Input: head = [2,1], x = 2 Output: [1,2]
Constraints:
- The number of nodes in the list is in the range
[0, 200].-100 <= Node.val <= 100-200 <= x <= 200
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
97. Remove Duplicates from Sorted List II (Leetcode:82)#
Problem Statement
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Example 1:
Input: head = [1,2,3,3,4,4,5] Output: [1,2,5]
Example 2:
Input: head = [1,1,1,2,3] Output: [2,3]
Constraints:
- The number of nodes in the list is in the range
[0, 300].-100 <= Node.val <= 100- The list is guaranteed to be sorted in ascending order.
Code and Explanation
- Dummy node handles duplicate runs at the head cleanly.
- Skip duplicate runs by advancing
headwhile values match. - Link distinct nodes through
prevwhen no duplicate run starts. - Time complexity: O(n)
- Space complexity: O(1)
98. 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)
99. Reverse Linked List II (Leetcode:92)#
Also in DSA Patterns
Reverse Linked List II — 07. Linked List (may include extra approaches and complexity analysis).
Problem Statement
Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5], left = 2, right = 4 Output: [1,4,3,2,5]
Example 2:
Input: head = [5], left = 1, right = 1 Output: [5]
Constraints:
- The number of nodes in the list is
n.1 <= n <= 500-500 <= Node.val <= 5001 <= left <= right <= n
Follow up: Could you do it in one pass?
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
100. 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.
101. Rotate List (Leetcode:61)#
Also in DSA Patterns
Rotate List — 07. Linked List (may include extra approaches and complexity analysis).
Problem Statement
Given the head of a linked list, rotate the list to the right by k places.
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
Example 2:
Input: head = [0,1,2], k = 4
Output: [2,0,1]
Constraints:
- The number of nodes in the list is in the range
[0, 500].-100 <= Node.val <= 1000 <= k <= 2 * 109
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.
Math & Geometry#
102. Factorial Trailing Zeroes (Leetcode:172)#
Problem Statement
Given an integer n, return the number of trailing zeroes in n!.
Example 1:
Input: n = 3 Output: 0
Example 2:
Input: n = 5 Output: 1
Constraints:
- 0 <= n <= 10^4
Code and Explanation
- Trailing zeros come from factors of 10, i.e. pairs of 2 and 5.
- There are always more factors of 2 than 5 in n!.
- Count how many multiples of 5, 25, 125, ... appear up to n.
103. Max Points on a Line (Leetcode:149)#
Also in DSA Patterns
Max Points on a Line — 21. Math and Geometry (may include extra approaches and complexity analysis).
Problem Statement
Given an array of points where points[i] = [xᵢ, yᵢ] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.
Example 1:
Input: points = [[1,1],[2,2],[3,3]]
Output: 3
Example 2:
Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Constraints:
1 <= points.length <= 300
points[i].length == 2
-10^4 <= xᵢ, yᵢ <= 10^4
All thepointsare unique.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
104. Palindrome Number (Leetcode:9)#
Problem Statement
Given an integer x, return true if x is a palindrome, and false otherwise.
Example 1:
Input: x = 121 Output: true Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Constraints:
-231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string?
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0: return False
div = 1
while x >= 10 * div:
div *= 10
while x:
right = x % 10
left = x // div
if left != right: return False
x = (x % div) // 10
div = div / 100
return True
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
105. 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.
106. 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.
107. Sqrt(x) (Leetcode:69)#
Also in DSA Patterns
Sqrt(x) — 09. Binary Search (may include extra approaches and complexity analysis).
Problem Statement
Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.
You must not use any built-in exponent function or operator.
- For example, do not use
pow(x, 0.5)in c++ orx ** 0.5in python.
Example 1:
Input: x = 4
Output: 2
Explanation: The square root of 4 is 2, so we return 2.
Example 2:
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
Constraints:
0 <= x <= 231 - 1
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
Matrix#
108. Game of Life (Leetcode:289)#
Problem Statement
According to the rules of Conway's Game of Life, simultaneously apply the next state to every cell in an m x n board of 0 (dead) and 1 (live) cells.
Example 1:
Input: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]] Output: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]
Constraints:
- m == board.length
- n == board[i].length
- 1 <= m, n <= 25
Code and Explanation
- Encode next state in bit 1 and keep current state in bit 0.
- Count live neighbors using only the lowest bit of each cell.
- Shift every cell right once to finalize the next generation.
109. 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)
110. 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)
111. 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)
112. 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#
113. 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))
114. Minimum Size Subarray Sum (Leetcode:209)#
Problem Statement
Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Example 1:
Input: target = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Example 2:
Input: target = 4, nums = [1,4,4] Output: 1
Example 3:
Input: target = 11, nums = [1,1,1,1,1,1,1,1] Output: 0
Constraints:
1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 104
Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log(n)).
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
res = float('inf')
l, total = 0, 0
for r in range(len(nums)):
total += nums[r]
while total >= target:
res = min(res, r - l + 1)
total -= nums[l]
l += 1
return res if res != float('inf') else 0
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
115. 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.
116. Substring with Concatenation of All Words (Leetcode:30)#
Also in DSA Patterns
Substring with Concatenation of All Words — 03. Sliding Window (may include extra approaches and complexity analysis).
Problem Statement
You are given a string s and an array of strings words. All the strings of words are of the same length.
A concatenated string is a string that exactly contains all the strings of any permutation of words concatenated.
- For example, if
words = ["ab","cd","ef"], then"abcdef","abefcd","cdabef","cdefab","efabcd", and"efcdab"are all concatenated strings."acdbef"is not a concatenated string because it is not the concatenation of any permutation ofwords.
Return an array of the starting indices of all the concatenated substrings in s. You can return the answer in any order.
Example 1:
Input: s = "barfoothefoobarman", words = ["foo","bar"] Output: [0,9] Explanation: The substring starting at 0 is
"barfoo". It is the concatenation of["bar","foo"]which is a permutation ofwords. The substring starting at 9 is"foobar". It is the concatenation of["foo","bar"]which is a permutation ofwords.
Example 2:
Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"] Output: [] Explanation: There is no concatenated substring.
Example 3:
Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"] Output: [6,9,12] Explanation: The substring starting at 6 is
"foobarthe". It is the concatenation of["foo","bar","the"]. The substring starting at 9 is"barthefoo". It is the concatenation of["bar","the","foo"]. The substring starting at 12 is"thefoobar". It is the concatenation of["the","foo","bar"].
Constraints:
1 <= s.length <= 1041 <= words.length <= 50001 <= words[i].length <= 30sandwords[i]consist 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.
Stack#
117. Basic Calculator (Leetcode:224)#
Also in DSA Patterns
Basic Calculator — 08. Stack (may include extra approaches and complexity analysis).
Problem Statement
Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Example 1:
Input: s = "1 + 1" Output: 2
Example 2:
Input: s = " 2-1 + 2 " Output: 3
Example 3:
Input: s = "(1+(4+5+2)-3)+(6+8)" Output: 23
Constraints:
1 <= s.length <= 3 * 105sconsists of digits,'+','-','(',')', and' '.srepresents a valid expression.'+'is not used as a unary operation (i.e.,"+1"and"+(2 + 3)"is invalid).'-'could be used as a unary operation (i.e.,"-1"and"-(2 + 3)"is valid).- There will be no two consecutive operators in the input.
- Every number and running calculation will fit in a signed 32-bit integer.
Code and Explanation
- Scan digits to build the current number and apply the current sign.
- On '(', push accumulated result and sign onto a stack.
- On ')', finalize the inner expression and combine with saved context.
118. 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.
119. Simplify Path (Leetcode:71)#
Problem Statement
You are given an absolute path for a Unix-style file system, which always begins with a slash '/'. Your task is to transform this absolute path into its simplified canonical path.
The rules of a Unix-style file system are as follows:
A single period
'.'represents the current directory.A double period
'..'represents the previous/parent directory.Multiple consecutive slashes such as
'//'and'///'are treated as a single slash'/'.Any sequence of periods that does not match the rules above should be treated as a valid directory or file name. For example,
'...'and'....'are valid directory or file names.
The simplified canonical path should follow these rules:
The path must start with a single slash
'/'.Directories within the path must be separated by exactly one slash
'/'.The path must not end with a slash
'/', unless it is the root directory.The path must not have any single or double periods (
'.'and'..') used to denote current or parent directories.
Return the simplified canonical path.
Example 1:
Input: path = "/home/"
Output: "/home"
Explanation:
The trailing slash should be removed.
Example 2:
Input: path = "/home//foo/"
Output: "/home/foo"
Explanation:
Multiple consecutive slashes are replaced by a single one.
Example 3:
Input: path = "/home/user/Documents/../Pictures"
Output: "/home/user/Pictures"
Explanation:
A double period ".." refers to the directory up a level (the parent directory).
Example 4:
Input: path = "/../"
Output: "/"
Explanation:
Going one level up from the root directory is not possible.
Example 5:
Input: path = "/.../a/../b/c/../d/./"
Output: "/.../b/d"
Explanation:
"..." is a valid name for a directory in this problem.
Constraints:
1 <= path.length <= 3000
pathconsists of English letters, digits, period'.', slash'/'or'_'.
pathis a valid absolute Unix path.
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
for i in path.split("/"):
# if i == "/" or i == '//', it becomes '' (empty string)
if i == "..":
if stack:
stack.pop()
elif i == "." or i == '':
# skip "." or an empty string
continue
else:
stack.append(i)
res = "/" + "/".join(stack)
return res
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
120. 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#
121. Average of Levels in Binary Tree (Leetcode:637)#
Problem Statement
Given the root of a binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: [3.0,14.5,11.0]
Constraints:
- The number of nodes in the tree is in the range
[1, 10^4].
Code and Explanation
- Use BFS with level-size snapshots.
- Sum node values at each level before moving deeper.
- Append total divided by level size to the answer.
122. Binary Search Tree Iterator (Leetcode:173)#
Also in DSA Patterns
Binary Search Tree Iterator — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree.
Example 1:
Input: ["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"], [[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []] Output: [null, 3, 7, true, 9, true, 15, true, 20, false]
Constraints:
- The number of nodes in the tree is in the range
[1, 10^5].
Code and Explanation
- Use a stack to simulate iterative in-order traversal.
- Initialize by pushing all left nodes from the root.
- On next(), pop the smallest node and push left chain of its right child.
123. 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)
124. 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)
125. 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.
126. Binary Tree Zigzag Level Order Traversal (Leetcode:103)#
Also in DSA Patterns
Binary Tree Zigzag Level Order Traversal — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: [[3],[20,9],[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].-100 <= Node.val <= 100
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
127. Construct Binary Tree from Inorder and Postorder Traversal (Leetcode:106)#
Also in DSA Patterns
Construct Binary Tree from Inorder and Postorder Traversal — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.
Example 1:
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]
Example 2:
Input: inorder = [-1], postorder = [-1]
Output: [-1]
Constraints:
1 <= inorder.length <= 3000postorder.length == inorder.length-3000 <= inorder[i], postorder[i] <= 3000inorderandpostorderconsist of unique values.- Each value of
postorderalso appears ininorder.inorderis guaranteed to be the inorder traversal of the tree.postorderis guaranteed to be the postorder traversal of the tree.
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
128. 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²)
129. Count Complete Tree Nodes (Leetcode:222)#
Also in DSA Patterns
Count Nodes in Complete Binary Tree — 11. Divide and Conquer (may include extra approaches and complexity analysis).
Problem Statement
Given the root of a complete binary tree, return the number of the nodes in the tree.
According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2^h nodes inclusive at the last level h.
Design an algorithm that runs in less than O(n) time complexity.
Example 1:
Input: root = [1,2,3,4,5,6]
Output: 6
Example 2:
Input: root = []
Output: 0
Example 3:
Input: root = [1]
Output: 1
Constraints:
- The number of nodes in the tree is in the range
[0, 5 * 10^4].0 <= Node.val <= 5 * 10^4- The tree is guaranteed to be complete.
Code and Explanation
- Measure left height and right height from the root.
- If equal, the tree is a perfect tree with 2^(h+1) - 1 nodes.
- Otherwise recurse on left and right subtrees and add 1 for the root.
130. Flatten Binary Tree to Linked List (Leetcode:114)#
Also in DSA Patterns
Flatten Binary Tree to Linked List — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given the root of a binary tree, flatten the tree into a "linked list" in-place using the same TreeNode class where the right child pointer points to the next node and the left child pointer is always null.
Example 1:
Input: root = [1,2,5,3,4,null,6] Output: [1,null,2,null,3,null,4,null,5,null,6]
Constraints:
- The number of nodes in the tree is in the range
[0, 200].
Code and Explanation
- Recursively flatten left and right subtrees first.
- Save the original right subtree, then attach the flattened left subtree to the right.
- Walk to the end of the new right chain and reconnect the saved right subtree.
131. 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)
132. 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)
133. Lowest Common Ancestor of a Binary Tree (Leetcode:236)#
Also in DSA Patterns
Lowest Common Ancestor in a Binary Tree — 11. Divide and Conquer (may include extra approaches and complexity analysis).
Problem Statement
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes p and q in the tree. The LCA is defined as the lowest node that has both p and q as descendants (where we allow a node to be a descendant of itself).
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3.
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 tree
Code and Explanation
- If node is p or q, return it.
- Search left and right subtrees.
- If both return non-null, current node is LCA; else propagate non-null side.
- Time complexity: O(n)
- Space complexity: O(h)
134. 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)
135. Minimum Absolute Difference in BST (Leetcode:530)#
Also in DSA Patterns
Minimum Absolute Difference in BST — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.
Example 1:
Input: root = [4,2,6,1,3]
Output: 1
Example 2:
Input: root = [1,0,48,null,null,12,49]
Output: 1
Constraints:
- The number of nodes in the tree is in the range
[2, 10⁴].0 <= Node.val <= 10⁵
Code and Explanation
- In-order traversal visits BST values in sorted order.
- Compare each node with its in-order predecessor.
- Track the smallest positive difference.
136. Path Sum (Leetcode:112)#
Also in DSA Patterns
Path Sum — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
A leaf is a node with no children.
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation:
The root-to-leaf path with the target sum is shown.
Example 2:
Input: root = [1,2,3], targetSum = 5
Output: false
Explanation:
There are two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
Example 3:
Input: root = [], targetSum = 0
Output: false
Explanation:
Since the tree is empty, there are no root-to-leaf paths.
Constraints:
- The number of nodes in the tree is in the range
[0, 5000].-1000 <= Node.val <= 1000-1000 <= targetSum <= 1000
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
137. Populating Next Right Pointers in Each Node II (Leetcode:117)#
Also in DSA Patterns
Populating Next Right Pointers in Each Node II — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given a binary tree, populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Each node has an additional next pointer.
Example 1:
Input: root = [1,2,3,4,5,null,7] Output: Nodes are connected level by level.
Constraints:
- The number of nodes in the tree is in the range
[0, 6000].
Code and Explanation
- Process the tree level by level using existing next pointers.
- Build the next level's linked list with a dummy head and tail.
- Advance head to the start of the next level and repeat.
138. 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)
139. Sum Root to Leaf Numbers (Leetcode:129)#
Also in DSA Patterns
Sum Root to Leaf Numbers — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path represents a number. Return the total sum of all root-to-leaf numbers.
Example 1:
Input: root = [1,2,3] Output: 25 Explanation: Paths 12 and 13 give 12 + 13 = 25.
Constraints:
- The number of nodes in the tree is in the range
[1, 1000].
Code and Explanation
- DFS while building the number along the current path.
- At a leaf, return the completed number.
- Sum results from left and right subtrees.
140. Symmetric Tree (Leetcode:101)#
Also in DSA Patterns
Symmetric Tree — 16. Tree (may include extra approaches and complexity analysis).
Problem Statement
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:
Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:
Input: root = [1,2,2,null,3,null,3]
Output: false
Constraints:
- The number of nodes in the tree is in the range
[1, 1000].-100 <= Node.val <= 100
Code and Explanation
- Official-style Python solution adapted for Brewing Intelligence sheets.
- Compare your approach with the reference implementation below.
141. 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#
142. 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)
143. 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)
144. 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#
145. 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)
146. 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)
147. Is Subsequence (Leetcode:392)#
Problem Statement
Given two strings s and t, return true if s is a subsequence of t, or false otherwise.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).
Example 1:
Input: s = "abc", t = "ahbgdc" Output: true Example 2:
Input: s = "axc", t = "ahbgdc" Output: false
Constraints:
0 <= s.length <= 100
0 <= t.length <= 104
sandtconsist only of lowercase English letters.
Follow up: Suppose there are lots of incoming s, say s_1_, s_2_, ..., s_k_ where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?
Code and Explanation
=== "Optimal"
```python linenums="1"
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
i, j = 0, 0
while i < len(s) and j < len(t):
if s[i] == t[j]:
i += 1
j += 1
return i == len(s)
```
**Explanation:**
1. Official-style Python solution adapted for Brewing Intelligence sheets.
2. Compare your approach with the reference implementation below.
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: 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: 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,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]
Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]
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: 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.