Questions 21–40 of 100 · 0 of 20 on this page marked learned
21.algorithms-0021Easyfresher
Maximum sum of k consecutive elements: find the largest total of any k consecutive values in a list, for example the best 3-day sales streak.
Sum the first k values, then slide the window one step at a time: add the value entering on the right and subtract the value leaving on the left. Each step is O(1), so the whole scan is O(n) instead of O(n x k) for re-summing every window.
Full answer
Problem
Given nums and k, return the largest sum of k consecutive elements.
Constraints: 1 <= k <= len(nums) <= 10^5; values may be negative. Invalid k raises ValueError.
Brute force
For each start index, sum the next k values: O(n x k). With n = 10^5 and k = 5 x 10^4 that is billions of additions.
Optimal approach
window = sum(nums[:k]), best = window.
For i from k to n - 1: window += nums[i] - nums[i - k], then update best.
Why it works
Two neighbouring windows share k - 1 elements. Moving from window [i - k, i - 1] to [i - k + 1, i] drops exactly nums[i - k] and adds exactly nums[i], so the running total is always the correct sum of the current window.
Complexity
O(n) time, O(1) space.
Code
python
def max_sum_window(nums, k):
"""Largest sum of any k consecutive values. Fixed-size sliding window, O(n)."""
if k <= 0 or k > len(nums):
raise ValueError("need 1 <= k <= len(nums)")
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k] # add the new day, drop the oldest
best = max(best, window)
return best
if __name__ == "__main__":
assert max_sum_window([2, 1, 5, 1, 3, 2], 3) == 9
assert max_sum_window([4, 2, 1, 7, 8, 1, 2, 8, 1, 0], 3) == 16
assert max_sum_window([5], 1) == 5
assert max_sum_window([-4, -2, -7], 2) == -6
assert max_sum_window([1, 2, 3], 3) == 6
for bad_k in (0, 4):
try:
max_sum_window([1, 2, 3], bad_k)
raise AssertionError("expected ValueError")
except ValueError:
pass
print("all tests passed")
Save as a21_max_sum_window.py and run python3 a21_max_sum_window.py. It prints all tests passed (Python 3.13.5).
Edge cases
k == len(nums) (one window). k == 1 (the maximum element). All negative values (the best is the least negative window, so do not initialise best to 0). k outside 1..n is rejected.
Pattern
Fixed-size sliding window: maintain an aggregate as the window moves by one. The same template computes moving averages, counts of vowels in every window, and anagram checks with letter counts.
python
def max_sum_window(nums, k):
"""Largest sum of any k consecutive values. Fixed-size sliding window, O(n)."""
if k <= 0 or k > len(nums):
raise ValueError("need 1 <= k <= len(nums)")
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k] # add the new day, drop the oldest
best = max(best, window)
return best
if __name__ == "__main__":
assert max_sum_window([2, 1, 5, 1, 3, 2], 3) == 9
assert max_sum_window([4, 2, 1, 7, 8, 1, 2, 8, 1, 0], 3) == 16
assert max_sum_window([5], 1) == 5
assert max_sum_window([-4, -2, -7], 2) == -6
assert max_sum_window([1, 2, 3], 3) == 6
for bad_k in (0, 4):
try:
max_sum_window([1, 2, 3], bad_k)
raise AssertionError("expected ValueError")
except ValueError:
pass
print("all tests passed")
Fixed window with an O(1) update per step; rejects k outside 1..len(nums).
Complexity
Time: O(n). Space: O(1). The brute force that re-sums each window is O(n * k).
By level
Fresher: Writes the brute force, then the sliding update, and traces the sales example. Should state O(n) time and O(1) space.
Mid: Handles negatives and invalid k cleanly and contrasts fixed windows with variable windows. Tests a window equal to the whole list.
Senior: Generalises to streaming moving aggregates, discusses numeric precision for floating-point averages and when a deque is needed for window maximum. Explains when a prefix sum array is a better fit for many queries.
Key points
Neighbouring windows share k - 1 elements
Update by adding the new element and subtracting the old one
Initialise best from the first window, not 0
O(n) time, O(1) space
Validate k
Common mistakes
Re-summing every window
Initialising best to 0 with negative inputs
Off-by-one on the index that leaves the window
Not handling k larger than the list
Follow-ups
How would you compute the average of every window?
What if you need the maximum element of each window instead of the sum?
What if the window size can vary?
Tips
Explain the shared-elements idea in one sentence
Trace two slides on the example
Test with negative numbers
Evaluation rubric
Correct O(n) algorithm
Correct initialisation
Handles invalid k
States complexity
22.algorithms-0022Mediumfresher
Longest substring without repeating characters: find the length of the longest substring in which no character repeats.
Grow a window with a right pointer and remember the last index of each character. When the new character was already seen inside the window, jump the left pointer to just after that earlier position. The window always contains unique characters, each pointer only moves forward, and the scan is O(n).
Full answer
Problem
Given a string s, return the length of the longest substring with all distinct characters.
Example: "abcabcbb" gives 3 ("abc"); "pwwkew" gives 3 ("wke"; "pwke" is a subsequence, not a substring).
Constraints: 0 <= len(s) <= 5 x 10^4; letters, digits, symbols and spaces.
Brute force
Check every substring for uniqueness with a set: O(n^3), or O(n^2) if you extend each start until a repeat appears.
Optimal approach
Keep left (window start) and a dictionary last_seen from character to its latest index.
For each right:
If s[right] is in last_seen and that index is at least left, set left = last_seen[s[right]] + 1.
Store last_seen[s[right]] = right.
Update best = max(best, right - left + 1).
Why it works
Invariant: s[left:right + 1] has no repeats. When a repeat appears, any window that still contains the earlier copy is invalid, so the left edge must move past it; moving further would only shrink the window for no reason. The check last_seen[ch] >= left matters: in "abba", when the second a arrives, the earlier a at index 0 is already outside the window [2, 3], and jumping back would be wrong.
Complexity
O(n) time. O(min(n, alphabet size)) space for the dictionary.
Code
python
def length_of_longest_substring(s):
"""Longest substring without repeating characters. Variable sliding window, O(n)."""
last_seen = {} # char -> last index
left = best = 0
for right, ch in enumerate(s):
if ch in last_seen and last_seen[ch] >= left:
left = last_seen[ch] + 1 # jump past the earlier copy
last_seen[ch] = right
best = max(best, right - left + 1)
return best
def brute(s):
return max((j - i for i in range(len(s)) for j in range(i, len(s) + 1)
if len(set(s[i:j])) == j - i), default=0)
if __name__ == "__main__":
for f in (length_of_longest_substring, brute):
assert f("abcabcbb") == 3
assert f("bbbbb") == 1
assert f("pwwkew") == 3
assert f("") == 0
assert f(" ") == 1
assert f("abba") == 2
assert f("dvdf") == 3
print("all tests passed")
Save as a22_longest_unique_substring.py and run python3 a22_longest_unique_substring.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty string returns 0. A single space returns 1. All identical characters returns 1. "abba" and "dvdf" test the "earlier copy outside the window" condition.
Pattern
Variable-size sliding window: expand on the right, shrink (or jump) on the left to restore the condition. The general template uses a while loop to shrink; here the last-seen index lets the left edge jump in one step.
python
def length_of_longest_substring(s):
"""Longest substring without repeating characters. Variable sliding window, O(n)."""
last_seen = {} # char -> last index
left = best = 0
for right, ch in enumerate(s):
if ch in last_seen and last_seen[ch] >= left:
left = last_seen[ch] + 1 # jump past the earlier copy
last_seen[ch] = right
best = max(best, right - left + 1)
return best
def brute(s):
return max((j - i for i in range(len(s)) for j in range(i, len(s) + 1)
if len(set(s[i:j])) == j - i), default=0)
if __name__ == "__main__":
for f in (length_of_longest_substring, brute):
assert f("abcabcbb") == 3
assert f("bbbbb") == 1
assert f("pwwkew") == 3
assert f("") == 0
assert f(" ") == 1
assert f("abba") == 2
assert f("dvdf") == 3
print("all tests passed")
Left edge jumps using a last-seen dictionary; a brute-force reference is tested on the same inputs.
Complexity
Time: O(n). Space: O(min(n, alphabet size)). Each pointer moves forward only, so the total work is linear.
By level
Fresher: Explains the window idea with a set and a shrinking loop, tracing "abcabcbb". Should state that both pointers only move forward.
Mid: Uses the last-seen jump, handles the stale-index case and generalises to at most k distinct characters. Explains why the check against the left edge matters for "abba".
Senior: Discusses alphabet size effects on memory, Unicode handling and a general template for variable windows with different validity conditions. Can explain how the method changes when the input is a stream of characters.
Key points
Window holds unique characters only
Store the last index of each character
Jump left past the earlier copy, only if it is inside the window
Both pointers move forward only
Substring is contiguous; subsequence is not
Common mistakes
Moving left backwards when the earlier copy is outside the window
Resetting the whole window on a repeat
Confusing substring with subsequence
Using a set and forgetting to remove characters as the window shrinks
Follow-ups
What if at most k distinct characters are allowed?
How would you return the substring itself?
What changes for Unicode text?
Tips
State the window invariant
Test "abba"
Explain why the algorithm is linear
Evaluation rubric
Correct O(n) algorithm
Handles the stale index case
Correct complexity
Clear invariant
23.algorithms-0023Mediummid
Find all anagrams of a pattern in a string: return every start index where a permutation of p appears in s.
An anagram of p has the same letter counts as p, so slide a window of length len(p) over s and keep letter counts for the window. Add the entering letter, remove the leaving letter, and compare the 26 counts with p's counts at each step. Each step is O(26) = O(1), giving O(n) overall instead of sorting every window.
Full answer
Problem
Given strings s and p (lowercase letters), return all indices i such that s[i:i + len(p)] is an anagram of p.
Example: s = "cbaebabacd", p = "abc" gives [0, 6] ("cba" and "bac").
Constraints: 1 <= len(s), len(p) <= 3 x 10^4.
Brute force
For each start, sort the window and compare with sorted p: O(n x m log m) for n = len(s), m = len(p).
Optimal approach
Count letters of p in need[26].
Slide over s, adding s[i] to have[26]. Once i >= m, subtract s[i - m], the letter that just left.
When have == need, record i - m + 1.
Why it works
Two strings of equal length are anagrams exactly when their letter counts match. The window always has length m after the first m steps, and the counts are updated incrementally, so each comparison checks precisely the current window.
An optimisation keeps a single counter of how many letters currently match (matches from 0 to 26) and updates it in O(1) per step instead of comparing arrays; useful for large alphabets.
Complexity
O(n x 26) = O(n) time, O(1) space (two arrays of 26).
Code
python
def find_anagrams(s, p):
"""Start indices of every anagram of p in s. Fixed window with counts, O(len(s))."""
if len(p) > len(s):
return []
need = [0] * 26
have = [0] * 26
for ch in p:
need[ord(ch) - 97] += 1
result = []
for i, ch in enumerate(s):
have[ord(ch) - 97] += 1
if i >= len(p):
have[ord(s[i - len(p)]) - 97] -= 1 # character leaving the window
if have == need: # 26 comparisons: O(1)
result.append(i - len(p) + 1)
return result
def brute(s, p):
k = len(p)
return [i for i in range(len(s) - k + 1) if sorted(s[i:i + k]) == sorted(p)]
if __name__ == "__main__":
for f in (find_anagrams, brute):
assert f("cbaebabacd", "abc") == [0, 6]
assert f("abab", "ab") == [0, 1, 2]
assert f("a", "ab") == []
assert f("aaaa", "a") == [0, 1, 2, 3]
assert f("xyz", "abc") == []
print("all tests passed")
Save as a23_find_anagrams.py and run python3 a23_find_anagrams.py. It prints all tests passed (Python 3.13.5).
Edge cases
p longer than s returns []. Overlapping answers ("abab", "ab" gives [0, 1, 2]). Single-character pattern. No matches. Uppercase or non-ASCII input needs a dictionary instead of a 26-slot array.
Pattern
Fixed-size sliding window with a frequency map. Closely related: permutation in string (return as soon as a match appears), and minimum window substring (variable size, "at least" counts).
python
def find_anagrams(s, p):
"""Start indices of every anagram of p in s. Fixed window with counts, O(len(s))."""
if len(p) > len(s):
return []
need = [0] * 26
have = [0] * 26
for ch in p:
need[ord(ch) - 97] += 1
result = []
for i, ch in enumerate(s):
have[ord(ch) - 97] += 1
if i >= len(p):
have[ord(s[i - len(p)]) - 97] -= 1 # character leaving the window
if have == need: # 26 comparisons: O(1)
result.append(i - len(p) + 1)
return result
def brute(s, p):
k = len(p)
return [i for i in range(len(s) - k + 1) if sorted(s[i:i + k]) == sorted(p)]
if __name__ == "__main__":
for f in (find_anagrams, brute):
assert f("cbaebabacd", "abc") == [0, 6]
assert f("abab", "ab") == [0, 1, 2]
assert f("a", "ab") == []
assert f("aaaa", "a") == [0, 1, 2, 3]
assert f("xyz", "abc") == []
print("all tests passed")
Two 26-slot count arrays compared in O(1) per step; a brute force with sorting is checked on the same tests.
Complexity
Time: O(n), with a constant factor of 26. Space: O(1). For large alphabets, track the number of matching counts to avoid comparing whole arrays.
By level
Fresher: Uses count arrays and a fixed window, and explains add and remove on the example. Should test a pattern longer than the text.
Mid: Implements cleanly, explains the O(1) comparison and handles overlapping results and edge cases. Explains the matches counter optimisation.
Senior: Optimises with a match counter for large alphabets and relates the method to rolling hashes and other fixed-window matching problems. Can explain how the method changes for uppercase letters or Unicode text.
Key points
Anagram of p = same letter counts
Window length is fixed at len(p)
Add the entering letter and remove the leaving one
Compare 26 counts in O(1)
Overlapping matches are all reported
Common mistakes
Sorting every window
Removing the wrong index when the window slides
Starting comparisons before the window is full
Assuming lowercase letters without stating it
Follow-ups
How would you return just whether any permutation exists?
How would you handle a large alphabet efficiently?
How does minimum window substring differ?
Tips
Say "same counts" before code
Trace the window on the example
Mention the matches-counter optimisation
Evaluation rubric
Correct O(n) sliding window
Correct handling of window boundaries
Handles p longer than s
Correct complexity
24.algorithms-0024Mediummid
Longest repeating character replacement: with at most k character changes, find the longest substring that can be turned into one repeated letter.
A window can become one letter if its length minus the count of its most frequent letter is at most k. Grow the window to the right; when that condition fails, shrink from the left. Keeping max_count as the highest count seen, even if it is briefly stale, is safe because the answer only grows when a larger max_count appears. O(n) time.
Full answer
Problem
Given an uppercase string s and an integer k, you may replace at most k characters with any letter. Return the length of the longest substring that can be made of one repeated letter.
Example: "AABABBA", k = 1 gives 4 (change one letter in "AABA" to get "AAAA").
While (right - left + 1) - max_count > k, decrement counts[s[left]] and move left right.
Update best.
Why it works
The cheapest way to make a window uniform is to keep its most frequent letter and change the rest, so length - max_count changes are needed. The window is valid exactly when that number is at most k.
Why max_count need not decrease when shrinking: the answer only improves if some window has a larger max_count than any seen before. A stale, too-large max_count can only keep the window at its current best length, never report a length that was not achievable earlier, because best was already set to that length when max_count was accurate. This makes the loop O(n) without recounting.
Complexity
O(n) time, O(26) = O(1) space.
Code
python
def character_replacement(s, k):
"""Longest substring that can become one repeated letter with at most k changes."""
counts = {}
left = max_count = best = 0
for right, ch in enumerate(s):
counts[ch] = counts.get(ch, 0) + 1
max_count = max(max_count, counts[ch])
while (right - left + 1) - max_count > k: # too many letters to change
counts[s[left]] -= 1
left += 1
best = max(best, right - left + 1)
return best
def brute(s, k):
best = 0
for i in range(len(s)):
for j in range(i, len(s)):
window = s[i:j + 1]
if len(window) - max(window.count(c) for c in set(window)) <= k:
best = max(best, len(window))
return best
if __name__ == "__main__":
for f in (character_replacement, brute):
assert f("ABAB", 2) == 4
assert f("AABABBA", 1) == 4
assert f("", 3) == 0
assert f("AAAA", 0) == 4
assert f("ABCDE", 0) == 1
assert f("ABCDE", 10) == 5
print("all tests passed")
Save as a24_char_replacement.py and run python3 a24_char_replacement.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty string returns 0. k = 0 gives the longest run of one letter. k >= len(s) gives len(s). All letters different with small k gives k + 1 (capped at length).
Pattern
Variable sliding window with a "cost to fix" condition. Related: longest subarray of 1s after flipping at most k zeros (count zeros instead of non-majority letters).
python
def character_replacement(s, k):
"""Longest substring that can become one repeated letter with at most k changes."""
counts = {}
left = max_count = best = 0
for right, ch in enumerate(s):
counts[ch] = counts.get(ch, 0) + 1
max_count = max(max_count, counts[ch])
while (right - left + 1) - max_count > k: # too many letters to change
counts[s[left]] -= 1
left += 1
best = max(best, right - left + 1)
return best
def brute(s, k):
best = 0
for i in range(len(s)):
for j in range(i, len(s)):
window = s[i:j + 1]
if len(window) - max(window.count(c) for c in set(window)) <= k:
best = max(best, len(window))
return best
if __name__ == "__main__":
for f in (character_replacement, brute):
assert f("ABAB", 2) == 4
assert f("AABABBA", 1) == 4
assert f("", 3) == 0
assert f("AAAA", 0) == 4
assert f("ABCDE", 0) == 1
assert f("ABCDE", 10) == 5
print("all tests passed")
Variable window that shrinks while length - max_count > k; a brute force is tested on the same inputs.
Complexity
Time: O(n). Space: O(1) (at most 26 counts). max_count is never decreased; this is safe because only a larger max_count can improve the answer.
By level
Fresher: Explains the validity condition and implements the window, recomputing the max count if needed. Should trace the window on "AABABBA" with k = 1.
Mid: Uses the non-decreasing max_count with a correct justification and solves the flip-zeros variant. Tests k = 0 and k larger than the string.
Senior: Generalises to weighted costs or larger alphabets, discusses when the monotonic trick is valid in other problems, and proves the window invariant carefully. Can explain when a stale maximum would be wrong in other window problems.
Key points
Window is valid when length - max_count <= k
Grow right, shrink left while invalid
Changes needed = letters that are not the majority
A stale max_count does not produce a wrong answer
O(n) time
Common mistakes
Recomputing the maximum count over 26 letters on every shrink without noting the cost
Shrinking with an if instead of a while in the general template
Forgetting the k >= length case
Thinking a stale max_count gives wrong answers without reasoning about it
Follow-ups
How would you solve max consecutive ones with k flips?
Can you return the substring itself?
What if replacements have different costs per letter?
Tips
Derive length - max_count before coding
Explain the stale max_count argument briefly
Test k = 0
Evaluation rubric
Correct condition and window logic
Correct O(n) reasoning
Handles edge cases
Explains the max_count subtlety or recomputes safely
25.algorithms-0025Hardsenior
Minimum window substring: find the shortest substring of s that contains every character of t, including repeats.
Count what t needs, then expand the right edge until the window covers all of it, tracked with a single "missing" counter. While the window is valid, record it and shrink from the left to find the smallest valid window ending here. Each pointer moves forward only, so the algorithm is O(|s| + |t|).
Full answer
Problem
Given s and t, return the minimum-length substring of s that contains every character of t with at least the same multiplicity. Return "" if none exists.
Example: s = "ADOBECODEBANC", t = "ABC" gives "BANC".
Constraints: 1 <= len(s), len(t) <= 10^5, upper and lowercase letters. The answer is unique.
Brute force
Check every substring for coverage: O(n^2) substrings, each checked in O(alphabet) with counts, O(n^2) or worse.
Optimal approach
need = Counter(t); missing = len(t).
For each right:
If need[s[right]] > 0, this character fills a gap: missing -= 1.
need[s[right]] -= 1 (it may go negative for surplus characters).
While missing == 0 (valid window):
Record the window if it is the shortest so far.
Give back s[left]: need[s[left]] += 1; if it becomes positive, the window now lacks it, so missing += 1.
left += 1.
Why it works
need[c] is the number of c still required (negative means surplus). missing is the total still required, so missing == 0 means the window covers t. For each right edge, shrinking until the window becomes invalid finds the shortest valid window ending at that edge. The overall minimum is among those, and both pointers only move forward, so every window that matters is examined.
Complexity
O(|s| + |t|) time. O(alphabet size) space.
Code
python
from collections import Counter
def min_window(s, t):
"""Smallest substring of s containing every character of t (with counts). O(|s| + |t|)."""
if not t or not s:
return ""
need = Counter(t)
missing = len(t) # characters of t still not covered
left = 0
best = (float("inf"), 0, 0) # (length, start, end exclusive)
for right, ch in enumerate(s):
if need[ch] > 0:
missing -= 1
need[ch] -= 1
while missing == 0: # window is valid: shrink from the left
if right - left + 1 < best[0]:
best = (right - left + 1, left, right + 1)
need[s[left]] += 1
if need[s[left]] > 0:
missing += 1
left += 1
return "" if best[0] == float("inf") else s[best[1]:best[2]]
def brute(s, t):
need = Counter(t)
best = ""
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
if not need - Counter(s[i:j]) and (not best or j - i < len(best)):
best = s[i:j]
return best if t else ""
if __name__ == "__main__":
for f in (min_window, brute):
assert f("ADOBECODEBANC", "ABC") == "BANC"
assert f("a", "a") == "a"
assert f("a", "aa") == ""
assert f("", "a") == ""
assert f("abc", "") == ""
assert f("aaflslflsldkalskaaa", "aaa") == "aaa"
print("all tests passed")
Save as a25_min_window.py and run python3 a25_min_window.py. It prints all tests passed (Python 3.13.5).
Edge cases
t longer than s or characters of t missing from s (return ""). Repeated characters in t ("aa" needs two as). Empty t returns "" by convention here. Case sensitivity: "a" and "A" are different.
Pattern
Variable window with "at least" counts and a single satisfied counter. The structure is the general sliding window template: expand until valid, then shrink while valid, updating the answer inside the shrink loop.
python
from collections import Counter
def min_window(s, t):
"""Smallest substring of s containing every character of t (with counts). O(|s| + |t|)."""
if not t or not s:
return ""
need = Counter(t)
missing = len(t) # characters of t still not covered
left = 0
best = (float("inf"), 0, 0) # (length, start, end exclusive)
for right, ch in enumerate(s):
if need[ch] > 0:
missing -= 1
need[ch] -= 1
while missing == 0: # window is valid: shrink from the left
if right - left + 1 < best[0]:
best = (right - left + 1, left, right + 1)
need[s[left]] += 1
if need[s[left]] > 0:
missing += 1
left += 1
return "" if best[0] == float("inf") else s[best[1]:best[2]]
def brute(s, t):
need = Counter(t)
best = ""
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
if not need - Counter(s[i:j]) and (not best or j - i < len(best)):
best = s[i:j]
return best if t else ""
if __name__ == "__main__":
for f in (min_window, brute):
assert f("ADOBECODEBANC", "ABC") == "BANC"
assert f("a", "a") == "a"
assert f("a", "aa") == ""
assert f("", "a") == ""
assert f("abc", "") == ""
assert f("aaflslflsldkalskaaa", "aaa") == "aaa"
print("all tests passed")
Single missing counter over a Counter of needs; a brute force is cross-checked on small cases.
Complexity
Time: O(|s| + |t|). Space: O(alphabet size). need values go negative for surplus characters, which is what makes the missing counter work.
By level
Fresher: Explains the expand-then-shrink idea with a count map and traces the example at a high level. Should test a t with repeated characters.
Mid: Implements the missing counter correctly, handles repeats and explains why the scan is linear. Records the answer inside the shrink loop.
Senior: Generalises the template, handles ordered variants (minimum window subsequence with DP or two pointers) and discusses streaming or very large alphabets. Can explain the cost of the method when the alphabet is large.
Key points
Count what t needs
Expand right until nothing is missing
Shrink left while still valid, recording the best
A single missing counter avoids comparing maps
O(|s| + |t|) time
Common mistakes
Ignoring repeated characters in t
Recording the window after shrinking past validity
Comparing whole count maps on every step
Moving left in an if instead of a while
Follow-ups
How would you return the count of such windows?
What if t's characters must appear in order?
How would you handle a stream of characters?
Tips
Explain the need map and missing counter first
Narrate expand and shrink phases
Test t with repeated characters
Evaluation rubric
Correct O(n) algorithm
Handles multiplicities
Records the best window correctly
Clear explanation of the invariant
26.algorithms-0026Hardsenior
Sliding window maximum: return the maximum of every window of size k as it slides across a list.
Keep a deque of indices whose values are strictly decreasing from front to back. When a new value arrives, pop smaller or equal values from the back, since they can never be a maximum while the new value is in the window; pop the front if it has left the window. The front is always the current maximum. Each index is pushed and popped at most once, so the total is O(n).
Full answer
Problem
Given nums and k, return a list of the maximum value in each window nums[i:i + k].
Compute max(nums[i:i + k]) for each window: O(n x k), which is 10^10 when n and k are both large.
A heap of (value, index) with lazy deletion of out-of-window entries gives O(n log n).
Optimal approach
Deque dq of indices, values decreasing.
For each index i:
While dq is not empty and nums[dq[-1]] <= nums[i], pop from the back.
Append i.
If dq[0] <= i - k, pop from the front (it left the window).
If i >= k - 1, the answer for this window is nums[dq[0]].
Why it works
If j < i and nums[j] <= nums[i], then j will leave the window before i and is never larger, so it can never be the maximum again; removing it is safe. That keeps values decreasing, so the front is the largest value among the indices still in the window. Out-of-window indices can only be at the front, because indices are added in increasing order.
Complexity
O(n) time: each index enters and leaves the deque at most once. O(k) space for the deque.
Code
python
from collections import deque
def max_sliding_window(nums, k):
"""Maximum of every window of size k using a monotonic deque. O(n)."""
if k <= 0:
raise ValueError("k must be positive")
dq = deque() # indices; their values strictly decrease
result = []
for i, x in enumerate(nums):
while dq and nums[dq[-1]] <= x:
dq.pop() # smaller values can never be a future maximum
dq.append(i)
if dq[0] <= i - k:
dq.popleft() # front index has left the window
if i >= k - 1:
result.append(nums[dq[0]])
return result
def brute(nums, k):
return [max(nums[i:i + k]) for i in range(len(nums) - k + 1)]
if __name__ == "__main__":
for f in (max_sliding_window, brute):
assert f([1, 3, -1, -3, 5, 3, 6, 7], 3) == [3, 3, 5, 5, 6, 7]
assert f([1], 1) == [1]
assert f([9, 8, 7, 6], 2) == [9, 8, 7]
assert f([4, 4, 4], 2) == [4, 4]
assert f([1, 2], 3) == []
print("all tests passed")
Save as a26_sliding_max.py and run python3 a26_sliding_max.py. It prints all tests passed (Python 3.13.5).
Edge cases
k == 1 (output equals input). k == len(nums) (one value). Equal values (popping with <= keeps only the latest index, which stays in the window longest). Decreasing input (deque grows to k). k larger than the list returns an empty list in this implementation; k <= 0 raises.
Pattern
Monotonic deque (monotonic queue). It also solves "shortest subarray with sum at least k" (with prefix sums), jump-game DP optimisations, and maximum of fixed windows in streaming metrics.
python
from collections import deque
def max_sliding_window(nums, k):
"""Maximum of every window of size k using a monotonic deque. O(n)."""
if k <= 0:
raise ValueError("k must be positive")
dq = deque() # indices; their values strictly decrease
result = []
for i, x in enumerate(nums):
while dq and nums[dq[-1]] <= x:
dq.pop() # smaller values can never be a future maximum
dq.append(i)
if dq[0] <= i - k:
dq.popleft() # front index has left the window
if i >= k - 1:
result.append(nums[dq[0]])
return result
def brute(nums, k):
return [max(nums[i:i + k]) for i in range(len(nums) - k + 1)]
if __name__ == "__main__":
for f in (max_sliding_window, brute):
assert f([1, 3, -1, -3, 5, 3, 6, 7], 3) == [3, 3, 5, 5, 6, 7]
assert f([1], 1) == [1]
assert f([9, 8, 7, 6], 2) == [9, 8, 7]
assert f([4, 4, 4], 2) == [4, 4]
assert f([1, 2], 3) == []
print("all tests passed")
Monotonic deque of indices; a brute force is checked on the same tests and in randomised cross-checks.
Complexity
Time: O(n). Space: O(k). A heap with lazy deletion would be O(n log n).
By level
Fresher: Explains the brute force and the idea of discarding smaller earlier values, then traces the deque on the example. Should explain why indices are stored rather than values.
Mid: Implements the deque correctly with index-based expiry and proves O(n). Handles equal values with a clear rule.
Senior: Applies monotonic queues to DP optimisation and prefix-sum problems, compares with heaps and sparse tables, and discusses streaming use. Explains where this structure speeds up dynamic programming.
Key points
Deque stores indices with decreasing values
Pop smaller or equal values from the back before pushing
Pop the front when it leaves the window
The front is the window maximum
Each index is pushed and popped once: O(n)
Common mistakes
Storing values instead of indices and losing track of the window
Forgetting to remove out-of-window indices
Claiming O(n k) is acceptable for large inputs
Popping only strictly smaller values and keeping stale duplicates without reason
Follow-ups
How would you get the window minimum?
How do you solve shortest subarray with sum at least k using a deque?
How would you compute window maxima on a stream with variable window size?
Tips
Explain why a smaller earlier value is useless
Store indices, not values
Give the amortised O(n) argument
Evaluation rubric
Correct deque algorithm
Correct amortised analysis
Handles window boundaries
Mentions heap alternative
27.algorithms-0027Easyfresher
Implement binary search on a sorted list, iteratively and recursively.
Keep a range [lo, hi] that must contain the target if it exists. Compare the middle element: equal means found, smaller means search the right half, larger means search the left half. Each step halves the range, so it takes O(log n) comparisons. The iterative version uses O(1) space; the recursive version uses O(log n) call stack.
Full answer
Problem
Given a sorted list nums and a target, return its index, or -1 if it is absent.
Constraints: 0 <= len(nums) <= 10^5, values distinct and sorted in increasing order.
Brute force
Linear scan: O(n). With 10^5 values and many queries, too slow.
Optimal approach
lo = 0, hi = len(nums) - 1.
While lo <= hi: mid = lo + (hi - lo) // 2.
nums[mid] == target: return mid.
nums[mid] < target: lo = mid + 1.
Otherwise: hi = mid - 1.
Return -1.
Looking up a word in a printed dictionary works the same way: open near the middle, decide which half, repeat.
Why it works
Invariant: if the target is present, its index is in [lo, hi]. Because the list is sorted, nums[mid] < target means everything at or before mid is too small, so lo = mid + 1 keeps the invariant; the other case is symmetric. The range shrinks every iteration, so the loop ends. When lo > hi the range is empty, so the target is absent.
lo + (hi - lo) // 2 avoids integer overflow in languages with fixed-width integers; in Python (lo + hi) // 2 is equally safe. Use //, not /, which would produce a float.
Complexity
O(log n) time. Iterative O(1) space; recursive O(log n) stack. For n = 10^5, at most 17 iterations.
Code
python
def binary_search(nums, target):
"""Index of target in sorted nums, or -1. O(log n) time, O(1) space."""
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2 # same as (lo + hi) // 2; avoids overflow in other languages
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
def binary_search_recursive(nums, target, lo=0, hi=None):
if hi is None:
hi = len(nums) - 1
if lo > hi:
return -1
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
return binary_search_recursive(nums, target, mid + 1, hi)
return binary_search_recursive(nums, target, lo, mid - 1)
if __name__ == "__main__":
marks = [35, 42, 58, 61, 77, 89, 94]
for f in (binary_search, binary_search_recursive):
assert f(marks, 61) == 3
assert f(marks, 35) == 0
assert f(marks, 94) == 6
assert f(marks, 60) == -1
assert f([], 5) == -1
assert f([5], 5) == 0
print("all tests passed")
Save as a27_binary_search.py and run python3 a27_binary_search.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty list. One element. Target at either end. Target smaller than all or larger than all values. Duplicates: this version returns any matching index; use lower bound to get the first one. Python's bisect module provides tested lower and upper bound functions.
Pattern
Binary search over a sorted range with a clear invariant. The same reasoning extends to lower and upper bounds, rotated arrays and binary search on the answer.
python
def binary_search(nums, target):
"""Index of target in sorted nums, or -1. O(log n) time, O(1) space."""
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2 # same as (lo + hi) // 2; avoids overflow in other languages
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
def binary_search_recursive(nums, target, lo=0, hi=None):
if hi is None:
hi = len(nums) - 1
if lo > hi:
return -1
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
return binary_search_recursive(nums, target, mid + 1, hi)
return binary_search_recursive(nums, target, lo, mid - 1)
if __name__ == "__main__":
marks = [35, 42, 58, 61, 77, 89, 94]
for f in (binary_search, binary_search_recursive):
assert f(marks, 61) == 3
assert f(marks, 35) == 0
assert f(marks, 94) == 6
assert f(marks, 60) == -1
assert f([], 5) == -1
assert f([5], 5) == 0
print("all tests passed")
Iterative and recursive versions tested on the same cases, including empty and single-element lists.
Complexity
Time: O(log n). Space: O(1) iterative; O(log n) recursive. For n = 10^5 at most 17 comparisons are needed.
By level
Fresher: Writes the iterative version with correct bounds and tests found, not found and boundary cases. Should test a target that is missing.
Mid: Explains the invariant, closed versus half-open conventions, and lower bound for duplicates. Uses bisect correctly when asked for library code.
Senior: Discusses overflow in other languages, branch-free and cache-friendly layouts, and generalising the invariant to any monotonic predicate. Explains why binary search can be slower than a scan on very small lists.
Key points
Keep [lo, hi] as the only place the target can be
Compare with the middle and discard half
O(log n) time
Use integer division
Iterative is O(1) space
Common mistakes
Using lo < hi with hi = len - 1 and missing the last element
Setting lo = mid instead of mid + 1 and looping forever
Using / and getting a float index
Running it on unsorted data
Follow-ups
How do you find the first occurrence of a duplicated value?
How would you search a rotated sorted list?
What is binary search on the answer?
Tips
State the invariant before code
Pick one convention (closed or half-open range) and stick to it
Test the ends and a missing value
Evaluation rubric
Correct loop bounds and updates
Clear invariant
Correct complexity
Handles edge cases
28.algorithms-0028Mediumfresher
Find the first and last position of a target in a sorted list with duplicates in O(log n) time.
Use lower bound twice. lower_bound(target) finds the first index whose value is at least target; if that value is the target, it is the first position. The last position is lower_bound(target + 1) - 1 for integers (or upper bound minus one in general). Both searches are O(log n), unlike scanning outwards from a match, which is O(n) when the target repeats many times.
Full answer
Problem
Given sorted integers nums and target, return [first, last] indices of target, or [-1, -1].
Constraints: 0 <= len(nums) <= 10^5, sorted non-decreasing. Must be O(log n).
Brute force
Scan for the first and last match: O(n). Or binary search for any match and walk outwards, which is O(n) when the whole list is the target.
Optimal approach
Lower bound with a half-open range [lo, hi):
lo = 0, hi = len(nums).
While lo < hi: mid = (lo + hi) // 2; if nums[mid] < target, lo = mid + 1, else hi = mid.
Return lo.
Then:
first = lower_bound(target); if first == len(nums) or nums[first] != target, return [-1, -1].
last = lower_bound(target + 1) - 1.
Why it works
Lower bound searches for the boundary of the predicate nums[i] >= target, which is false then true across a sorted list. The loop keeps "everything before lo is false" and "everything from hi onwards is true", and stops when they meet at the first true position. For integers, the first index with value at least target + 1 is one past the last target.
This is what bisect.bisect_left and bisect.bisect_right compute; the test checks the hand-written version against bisect.
Complexity
Two binary searches: O(log n) time, O(1) space.
Code
python
def lower_bound(nums, target):
"""First index i with nums[i] >= target (len(nums) if none)."""
lo, hi = 0, len(nums) # search in the half-open range [lo, hi)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
def search_range(nums, target):
"""[first, last] index of target in sorted nums, or [-1, -1]. O(log n)."""
first = lower_bound(nums, target)
if first == len(nums) or nums[first] != target:
return [-1, -1]
last = lower_bound(nums, target + 1) - 1 # integers: first value > target
return [first, last]
if __name__ == "__main__":
import bisect
assert search_range([5, 7, 7, 8, 8, 10], 8) == [3, 4]
assert search_range([5, 7, 7, 8, 8, 10], 6) == [-1, -1]
assert search_range([], 0) == [-1, -1]
assert search_range([2, 2, 2], 2) == [0, 2]
assert search_range([1], 1) == [0, 0]
data = [1, 3, 3, 3, 9]
for x in range(0, 11):
assert lower_bound(data, x) == bisect.bisect_left(data, x)
print("all tests passed")
Save as a28_first_last.py and run python3 a28_first_last.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty list. Target absent but between values, below all, or above all. All elements equal to the target ([0, n - 1]). A single element. For non-integer keys, replace target + 1 with an upper bound search using <= in the comparison.
Pattern
Binary search for a boundary (first true of a monotonic predicate). It is the base for counting occurrences, insert position, and binary search on the answer.
python
def lower_bound(nums, target):
"""First index i with nums[i] >= target (len(nums) if none)."""
lo, hi = 0, len(nums) # search in the half-open range [lo, hi)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
def search_range(nums, target):
"""[first, last] index of target in sorted nums, or [-1, -1]. O(log n)."""
first = lower_bound(nums, target)
if first == len(nums) or nums[first] != target:
return [-1, -1]
last = lower_bound(nums, target + 1) - 1 # integers: first value > target
return [first, last]
if __name__ == "__main__":
import bisect
assert search_range([5, 7, 7, 8, 8, 10], 8) == [3, 4]
assert search_range([5, 7, 7, 8, 8, 10], 6) == [-1, -1]
assert search_range([], 0) == [-1, -1]
assert search_range([2, 2, 2], 2) == [0, 2]
assert search_range([1], 1) == [0, 0]
data = [1, 3, 3, 3, 9]
for x in range(0, 11):
assert lower_bound(data, x) == bisect.bisect_left(data, x)
print("all tests passed")
A half-open lower_bound used twice; the test compares it with bisect.bisect_left on every value.
Complexity
Time: O(log n). Space: O(1). Walking outward from one match would be O(n) in the worst case.
By level
Fresher: Writes two binary searches, one biased left and one biased right, and tests duplicates and an absent target. Should test a list made entirely of the target.
Mid: Expresses it as lower and upper bound with a clear predicate and compares with bisect. Explains the half-open range convention.
Senior: Generalises boundary search to arbitrary monotonic predicates and non-integer keys, and discusses API design for range queries on sorted data. Can explain how the boundary search works on non-integer keys.
Key points
Lower bound finds the first index with value >= target
Half-open range [lo, hi) with hi = mid avoids skipping the answer
Last position = lower_bound(target + 1) - 1 for integers
bisect_left and bisect_right are the library versions
Both searches are O(log n)
Common mistakes
Walking outward from a match
Mixing closed and half-open conventions in one loop
Not checking that nums[first] is the target
Using target + 1 for floats or strings
Follow-ups
How many times does the target occur?
How would you find the insert position for a new value?
How do you write upper bound directly?
Tips
Frame it as "first true of a predicate"
Show the library equivalent
Test a list made entirely of the target
Evaluation rubric
Correct boundary searches
Correct handling of absent target
O(log n) overall
Consistent loop convention
29.algorithms-0029Mediummid
Search in a rotated sorted list: find a target in a sorted list of distinct values that has been rotated at an unknown pivot.
In a rotated sorted list, at least one half around mid is always sorted. Check which half is sorted by comparing nums[lo] with nums[mid], then test whether the target lies inside that sorted half's range; if so search it, otherwise search the other half. This keeps O(log n) time without first finding the rotation point.
Full answer
Problem
A sorted list of distinct values was rotated, for example [0, 1, 2, 4, 5, 6, 7] became [4, 5, 6, 7, 0, 1, 2]. Given the rotated list and a target, return its index or -1 in O(log n).
Two-step alternative: binary search for the rotation point (the minimum), then do a normal binary search in the correct part. Also O(log n), with two loops.
Optimal approach
While lo <= hi:
mid = (lo + hi) // 2; return mid if it matches.
If nums[lo] <= nums[mid], the left half [lo, mid] is sorted:
If nums[lo] <= target < nums[mid], search left (hi = mid - 1); else search right.
Otherwise the right half [mid, hi] is sorted:
If nums[mid] < target <= nums[hi], search right (lo = mid + 1); else search left.
Why it works
A rotation creates at most one "drop" in the list. The drop is either in the left half or the right half, not both, so one half is sorted. For a sorted half, a range check tells you exactly whether the target can be there. If not, it can only be in the other half. The search range halves each step, preserving the invariant that the target, if present, is in [lo, hi].
<= in nums[lo] <= nums[mid] matters when lo == mid (a range of one or two elements).
Complexity
O(log n) time, O(1) space.
Code
python
def search_rotated(nums, target):
"""Search a rotated sorted list of distinct values. O(log n)."""
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[lo] <= nums[mid]: # left half is sorted
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else: # right half is sorted
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1
if __name__ == "__main__":
assert search_rotated([4, 5, 6, 7, 0, 1, 2], 0) == 4
assert search_rotated([4, 5, 6, 7, 0, 1, 2], 3) == -1
assert search_rotated([1], 0) == -1
assert search_rotated([1], 1) == 0
assert search_rotated([], 1) == -1
assert search_rotated([3, 1], 1) == 1
base = list(range(10))
for r in range(10): # every rotation, every value
rotated = base[r:] + base[:r]
for x in base:
assert search_rotated(rotated, x) == rotated.index(x)
print("all tests passed")
Save as a29_rotated_search.py and run python3 a29_rotated_search.py. It prints all tests passed (Python 3.13.5).
Edge cases
Not rotated at all. Rotated by one. Two elements ([3, 1]). One element. Empty list. The test runs every rotation of 0 to 9 and every target. With duplicates allowed ([1, 1, 1, 0, 1]), you cannot always tell which half is sorted; the fix is to shrink lo and hi when nums[lo] == nums[mid] == nums[hi], which degrades the worst case to O(n).
Pattern
Binary search with a "which half is ordered" decision. Related: find the minimum of a rotated list and find a peak element, both of which binary search on a local property rather than a target value.
python
def search_rotated(nums, target):
"""Search a rotated sorted list of distinct values. O(log n)."""
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[lo] <= nums[mid]: # left half is sorted
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else: # right half is sorted
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1
if __name__ == "__main__":
assert search_rotated([4, 5, 6, 7, 0, 1, 2], 0) == 4
assert search_rotated([4, 5, 6, 7, 0, 1, 2], 3) == -1
assert search_rotated([1], 0) == -1
assert search_rotated([1], 1) == 0
assert search_rotated([], 1) == -1
assert search_rotated([3, 1], 1) == 1
base = list(range(10))
for r in range(10): # every rotation, every value
rotated = base[r:] + base[:r]
for x in base:
assert search_rotated(rotated, x) == rotated.index(x)
print("all tests passed")
One-loop binary search choosing the sorted half; the tests check every rotation of a 10-element list.
Complexity
Time: O(log n). Space: O(1). With duplicates allowed, the worst case becomes O(n).
By level
Fresher: Explains why one half is sorted and implements the search, testing the example and a two-element list. Should test a list that is not rotated.
Mid: Handles boundary conditions carefully, gives the two-step alternative and explains the duplicate case. Tests two-element lists and targets at the rotation point.
Senior: Proves the invariant, analyses the duplicate worst case and connects the technique to other local-property binary searches. Can explain why the same idea finds the minimum of a rotated list.
Key points
At least one half around mid is sorted
Use nums[lo] <= nums[mid] to detect a sorted left half
Range-check the target in the sorted half
Otherwise search the other half
Duplicates break the guarantee and can force O(n)
Common mistakes
Using < instead of <= and failing on two-element ranges
Range checks with wrong inclusive bounds
Finding the pivot with a linear scan
Claiming O(log n) when duplicates are allowed
Follow-ups
How would you find the rotation point itself?
What changes with duplicates?
How would you find the minimum element?
Tips
Draw the rotated list as two rising slopes
Explain the sorted-half test first
Test all small rotations
Evaluation rubric
Correct single-pass binary search
Correct inclusive range checks
Handles small arrays
Discusses duplicates
30.algorithms-0030Mediummid
Koko eating bananas: find the minimum eating speed that lets someone finish all piles within h hours, using binary search on the answer.
If speed k works, any faster speed also works, so "can finish at speed k" is a monotonic predicate over k from 1 to max(pile). Binary search for the smallest k that passes; each check sums ceil(pile / k) in O(n). Total O(n log M) where M is the largest pile, instead of trying every speed.
Full answer
Problem
There are piles of bananas. Each hour, Koko picks one pile and eats up to k bananas from it (if the pile has fewer, she finishes it and waits for the next hour). Return the minimum integer k that lets her finish within hours.
Constraints: 1 <= len(piles) <= 10^4, len(piles) <= hours <= 10^9, piles up to 10^9.
Brute force
Try k = 1, 2, 3, ... until it works: O(n x M), which is impossible for M = 10^9.
Optimal approach
The answer lies in [1, max(piles)]: speed max(piles) finishes each pile in one hour, which is enough since hours >= len(piles).
hours_needed(k) = sum(ceil(p / k)), computed as (p + k - 1) // k to stay in integers.
Binary search: if hours_needed(mid) <= hours, then mid works and the answer is at most mid (hi = mid); otherwise lo = mid + 1.
When lo == hi, that is the smallest working speed.
Why it works
hours_needed(k) never increases as k grows, so the predicate "finishes in time" is false for small k and true from some point on. Binary search finds the first true value of a monotonic predicate, exactly as lower bound finds the first index with value at least a target.
Complexity
O(n log M) time, where M = max(piles): about 30 iterations for M = 10^9, each O(n). O(1) space.
Code
python
def min_eating_speed(piles, hours):
"""Smallest integer speed k so all piles are eaten within `hours` hours.
Binary search on the answer: feasibility is monotonic in k.
"""
if hours < len(piles):
raise ValueError("need at least one hour per pile")
def hours_needed(k):
return sum((p + k - 1) // k for p in piles) # ceil(p / k) without floats
lo, hi = 1, max(piles)
while lo < hi:
mid = (lo + hi) // 2
if hours_needed(mid) <= hours:
hi = mid # mid works; maybe something smaller also works
else:
lo = mid + 1
return lo
def brute(piles, hours):
k = 1
while sum((p + k - 1) // k for p in piles) > hours:
k += 1
return k
if __name__ == "__main__":
for f in (min_eating_speed, brute):
assert f([3, 6, 7, 11], 8) == 4
assert f([30, 11, 23, 4, 20], 5) == 30
assert f([30, 11, 23, 4, 20], 6) == 23
assert f([1], 1) == 1
assert min_eating_speed([1000000000], 2) == 500000000 # large pile: log steps only
try:
min_eating_speed([1, 2, 3], 2)
raise AssertionError("expected ValueError")
except ValueError:
pass
print("all tests passed")
Save as a30_koko.py and run python3 a30_koko.py. It prints all tests passed (Python 3.13.5).
Edge cases
One pile. hours == len(piles) (answer is the largest pile). Very large piles (integer ceiling avoids float rounding errors). hours < len(piles) is impossible and raises ValueError.
Pattern
Binary search on the answer: when you cannot search the input directly but can check "is answer x feasible?" and feasibility is monotonic. Other examples: capacity to ship packages, split array largest sum, minimum days to make bouquets, integer square root.
python
def min_eating_speed(piles, hours):
"""Smallest integer speed k so all piles are eaten within `hours` hours.
Binary search on the answer: feasibility is monotonic in k.
"""
if hours < len(piles):
raise ValueError("need at least one hour per pile")
def hours_needed(k):
return sum((p + k - 1) // k for p in piles) # ceil(p / k) without floats
lo, hi = 1, max(piles)
while lo < hi:
mid = (lo + hi) // 2
if hours_needed(mid) <= hours:
hi = mid # mid works; maybe something smaller also works
else:
lo = mid + 1
return lo
def brute(piles, hours):
k = 1
while sum((p + k - 1) // k for p in piles) > hours:
k += 1
return k
if __name__ == "__main__":
for f in (min_eating_speed, brute):
assert f([3, 6, 7, 11], 8) == 4
assert f([30, 11, 23, 4, 20], 5) == 30
assert f([30, 11, 23, 4, 20], 6) == 23
assert f([1], 1) == 1
assert min_eating_speed([1000000000], 2) == 500000000 # large pile: log steps only
try:
min_eating_speed([1, 2, 3], 2)
raise AssertionError("expected ValueError")
except ValueError:
pass
print("all tests passed")
Integer ceiling division in the feasibility check; a brute force over speeds is cross-checked on small inputs.
Complexity
Time: O(n log M), M = max(piles). Space: O(1). About 30 binary search steps when piles reach 10^9.
By level
Fresher: Writes the feasibility check, notices that faster speeds are always fine and applies binary search over speeds. Should explain why speed max(piles) always works.
Mid: Sets correct bounds, uses integer ceiling and explains the first-true search. Tests the case where hours equals the number of piles.
Senior: Generalises binary search on the answer, including real-valued answers with a precision stop, and identifies when the predicate is not monotonic. Can explain how to stop a real-valued version with a precision limit.
Key points
Feasibility is monotonic in speed
Search the speed range [1, max(piles)]
Check cost is sum of ceil(pile / k)
Use integer ceiling (p + k - 1) // k
O(n log M) total
Common mistakes
Trying every speed
Using floating-point ceil and getting rounding errors on big values
Wrong search bounds such as starting at 0
Using hi = mid - 1 when mid works and skipping the answer
Follow-ups
How would you solve capacity to ship packages within d days?
What if speeds could be real numbers?
How do you choose the bounds in general?
Tips
Say "is speed k feasible?" out loud
Justify monotonicity before searching
State the bounds and why they are safe
Evaluation rubric
Correct monotonic predicate and bounds
Correct binary search for the first feasible value
Correct complexity
Handles large values
31.algorithms-0031Hardsenior
Capacity to ship packages within d days: find the smallest ship capacity that sends weighted packages, in order, within a given number of days.
For a fixed capacity, a greedy pass counts the days needed: load packages in order and start a new day when the next one would overflow. More capacity never needs more days, so binary search the capacity between max(weights) and sum(weights). This is the same problem as "split array largest sum": minimise the largest contiguous part when cutting into at most d parts.
Full answer
Problem
Packages with weights must be shipped in the given order. Each day the ship carries a contiguous run of packages whose total does not exceed its capacity. Return the least capacity that ships everything within days days.
Constraints: 1 <= days <= len(weights) <= 5 x 10^4 (more days than packages also works: the answer is then the largest weight), 1 <= weights[i] <= 500.
Brute force
Try every way to cut the list into at most days contiguous parts and take the smallest maximum part: exponential, about C(n - 1, d - 1) partitions. The test uses it as a reference for tiny inputs.
A DP over (prefix, parts) is O(n^2 x d), still too slow for n = 5 x 10^4.
Optimal approach
Bounds: lo = max(weights) (the heaviest package must fit), hi = sum(weights) (one day).
days_needed(c): greedy pass; add packages to today's load until the next one would exceed c, then start a new day.
Binary search for the smallest c with days_needed(c) <= days.
Why it works
Greedy is optimal for a fixed capacity: filling each day as much as possible can only push later cuts further right, so it never uses more days than any other valid schedule (an exchange argument). The predicate "capacity c is enough" is monotonic, since a larger ship can follow the same schedule. Binary search finds the first capacity where the predicate becomes true.
Complexity
O(n log S) time, where S = sum(weights): at most about 25 iterations for S = 2.5 x 10^7, each O(n). O(1) space.
Code
python
def ship_within_days(weights, days):
"""Least ship capacity to send packages in order within `days` days."""
def days_needed(capacity):
used, load = 1, 0
for w in weights:
if load + w > capacity: # start a new day
used += 1
load = 0
load += w
return used
lo, hi = max(weights), sum(weights) # must carry the heaviest; never need more than all
while lo < hi:
mid = (lo + hi) // 2
if days_needed(mid) <= days:
hi = mid
else:
lo = mid + 1
return lo
def brute(weights, days):
from itertools import combinations
n = len(weights)
best = sum(weights)
for cuts in range(min(days, n)):
for pos in combinations(range(1, n), cuts):
bounds = (0,) + pos + (n,)
best = min(best, max(sum(weights[a:b]) for a, b in zip(bounds, bounds[1:])))
return best
if __name__ == "__main__":
for f in (ship_within_days, brute):
assert f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5) == 15
assert f([3, 2, 2, 4, 1, 4], 3) == 6
assert f([1, 2, 3, 1, 1], 4) == 3
assert f([7], 1) == 7
assert f([7, 2, 5, 10, 8], 2) == 18
assert f([1, 1, 1], 10) == 1
print("all tests passed")
Save as a31_ship_packages.py and run python3 a31_ship_packages.py. It prints all tests passed (Python 3.13.5).
Edge cases
One package. days >= len(weights) (answer is the largest weight). days == 1 (answer is the total). Equal weights. Starting lo at 0 or 1 instead of max(weights) still terminates, but the greedy check must then handle a package larger than capacity; starting at the maximum avoids that case.
Pattern
Binary search on the answer with a greedy feasibility check. The same pattern solves split array largest sum, allocating books to students, painters' partition and minimising the maximum distance between gas stations.
python
def ship_within_days(weights, days):
"""Least ship capacity to send packages in order within `days` days."""
def days_needed(capacity):
used, load = 1, 0
for w in weights:
if load + w > capacity: # start a new day
used += 1
load = 0
load += w
return used
lo, hi = max(weights), sum(weights) # must carry the heaviest; never need more than all
while lo < hi:
mid = (lo + hi) // 2
if days_needed(mid) <= days:
hi = mid
else:
lo = mid + 1
return lo
def brute(weights, days):
from itertools import combinations
n = len(weights)
best = sum(weights)
for cuts in range(min(days, n)):
for pos in combinations(range(1, n), cuts):
bounds = (0,) + pos + (n,)
best = min(best, max(sum(weights[a:b]) for a, b in zip(bounds, bounds[1:])))
return best
if __name__ == "__main__":
for f in (ship_within_days, brute):
assert f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5) == 15
assert f([3, 2, 2, 4, 1, 4], 3) == 6
assert f([1, 2, 3, 1, 1], 4) == 3
assert f([7], 1) == 7
assert f([7, 2, 5, 10, 8], 2) == 18
assert f([1, 1, 1], 10) == 1
print("all tests passed")
Greedy day counter plus binary search; an exhaustive partition search checks the same tests.
Complexity
Time: O(n log S), S = sum(weights). Space: O(1). The exhaustive brute force is exponential and is used only as a test reference.
By level
Fresher: Writes the greedy day counter and searches capacities with binary search, testing the example. Should explain why the lower bound is the heaviest package.
Mid: Justifies the greedy with an exchange argument, chooses tight bounds and connects to split array largest sum. Explains why the greedy count is optimal for a fixed capacity.
Senior: Compares with DP formulations, discusses reordering (which becomes bin packing and NP-hard) and real-valued variants. Explains why the reordered version becomes a much harder problem.
Key points
Feasibility for a fixed capacity is a greedy pass
Larger capacity never needs more days: monotonic
Bounds are max(weights) and sum(weights)
Binary search the first feasible capacity
Same problem as split array largest sum
Common mistakes
Lower bound below the heaviest package
Reordering packages
Off-by-one in counting days (start with 1 day)
Using hi = mid - 1 when mid is feasible
Follow-ups
How would you return the actual split?
What if packages could be reordered?
How does this relate to the painters' partition problem?
Tips
State the bounds and justify each
Explain why greedy is optimal for a fixed capacity
Mention the split array equivalence
Evaluation rubric
Correct bounds and greedy check
Correct binary search
Justifies monotonicity and greedy
Correct complexity
32.algorithms-0032Hardsenior
Median of two sorted arrays: find the median of two sorted lists in O(log(min(m, n))) time without merging them.
Binary search how many elements the left half takes from the shorter list; the rest of the left half comes from the longer list. A cut is correct when every value on the left is at most every value on the right, which needs only two cross comparisons. The median is then read from the four values around the cut. This runs in O(log(min(m, n))) time and O(1) space.
Full answer
Problem
Given sorted lists a (length m) and b (length n), return the median of all m + n values as a float.
Example: a = [1, 3], b = [2] gives 2.0; a = [1, 2], b = [3, 4] gives 2.5.
Constraints: 0 <= m, n <= 1000, m + n >= 1 (both empty raises ValueError), required time O(log(m + n)) or better.
Brute force
Merge (or concatenate and sort) and pick the middle: O(m + n) with a merge, O((m + n) log(m + n)) with sorting. The test uses this as the reference.
Optimal approach
Make a the shorter list. Let half = (m + n + 1) // 2, the size of the left part.
Binary search i in [0, m], the count taken from a; then j = half - i from b.
Read the edge values, using minus and plus infinity past the ends: a_left = a[i - 1], a_right = a[i], b_left = b[j - 1], b_right = b[j].
If a_left <= b_right and b_left <= a_right, the cut is correct:
odd total: median is max(a_left, b_left);
even total: (max(a_left, b_left) + min(a_right, b_right)) / 2.
If a_left > b_right, too many were taken from a: hi = i - 1. Otherwise lo = i + 1.
Why it works
The median splits the combined values into a left part of size half and a right part, with every left value at most every right value. Each list is already sorted, so only the cross pairs (a_left with b_right, b_left with a_right) can violate that. As i grows, a_left grows and b_right shrinks, so the violations are monotonic in i, which makes binary search valid. Searching the shorter list keeps j in [0, n].
Complexity
O(log(min(m, n))) time, O(1) space.
Code
python
def find_median_sorted_arrays(a, b):
"""Median of two sorted lists in O(log(min(m, n))) by binary searching a partition."""
if len(a) > len(b):
a, b = b, a # binary search the shorter list
m, n = len(a), len(b)
if m + n == 0:
raise ValueError("both lists are empty")
half = (m + n + 1) // 2 # size of the left part
lo, hi = 0, m
while lo <= hi:
i = (lo + hi) // 2 # take i items from a ...
j = half - i # ... and j items from b
a_left = a[i - 1] if i > 0 else float("-inf")
a_right = a[i] if i < m else float("inf")
b_left = b[j - 1] if j > 0 else float("-inf")
b_right = b[j] if j < n else float("inf")
if a_left <= b_right and b_left <= a_right:
if (m + n) % 2:
return float(max(a_left, b_left))
return (max(a_left, b_left) + min(a_right, b_right)) / 2
if a_left > b_right:
hi = i - 1 # took too many from a
else:
lo = i + 1 # took too few from a
raise AssertionError("inputs must be sorted")
def brute(a, b):
c = sorted(a + b)
mid = len(c) // 2
return float(c[mid]) if len(c) % 2 else (c[mid - 1] + c[mid]) / 2
if __name__ == "__main__":
for f in (find_median_sorted_arrays, brute):
assert f([1, 3], [2]) == 2.0
assert f([1, 2], [3, 4]) == 2.5
assert f([], [1]) == 1.0
assert f([0, 0], [0, 0]) == 0.0
assert f([2], []) == 2.0
assert f([1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]) == 6.0
try:
find_median_sorted_arrays([], [])
raise AssertionError("expected ValueError")
except ValueError:
pass
print("all tests passed")
Save as a32_median_two_arrays.py and run python3 a32_median_two_arrays.py. It prints all tests passed (Python 3.13.5).
Edge cases
One list empty. All values equal. All of a smaller than all of b (cut at an end, handled by the infinities). Odd and even totals. Both empty is rejected. Unsorted input breaks the precondition; the code raises AssertionError if no valid cut is found.
Pattern
Binary search on a partition position. The generalisation is "k-th smallest of two sorted arrays", solved by discarding about k / 2 elements per step.
python
def find_median_sorted_arrays(a, b):
"""Median of two sorted lists in O(log(min(m, n))) by binary searching a partition."""
if len(a) > len(b):
a, b = b, a # binary search the shorter list
m, n = len(a), len(b)
if m + n == 0:
raise ValueError("both lists are empty")
half = (m + n + 1) // 2 # size of the left part
lo, hi = 0, m
while lo <= hi:
i = (lo + hi) // 2 # take i items from a ...
j = half - i # ... and j items from b
a_left = a[i - 1] if i > 0 else float("-inf")
a_right = a[i] if i < m else float("inf")
b_left = b[j - 1] if j > 0 else float("-inf")
b_right = b[j] if j < n else float("inf")
if a_left <= b_right and b_left <= a_right:
if (m + n) % 2:
return float(max(a_left, b_left))
return (max(a_left, b_left) + min(a_right, b_right)) / 2
if a_left > b_right:
hi = i - 1 # took too many from a
else:
lo = i + 1 # took too few from a
raise AssertionError("inputs must be sorted")
def brute(a, b):
c = sorted(a + b)
mid = len(c) // 2
return float(c[mid]) if len(c) % 2 else (c[mid - 1] + c[mid]) / 2
if __name__ == "__main__":
for f in (find_median_sorted_arrays, brute):
assert f([1, 3], [2]) == 2.0
assert f([1, 2], [3, 4]) == 2.5
assert f([], [1]) == 1.0
assert f([0, 0], [0, 0]) == 0.0
assert f([2], []) == 2.0
assert f([1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]) == 6.0
try:
find_median_sorted_arrays([], [])
raise AssertionError("expected ValueError")
except ValueError:
pass
print("all tests passed")
Partition binary search on the shorter list with infinity sentinels; a sort-based reference is tested on the same inputs.
Complexity
Time: O(log(min(m, n))). Space: O(1). Merging would be O(m + n); the partition search avoids reading most elements.
By level
Fresher: Gives the merge solution, then explains the idea of cutting both lists so the left halves have the right size. Should state the cost of the merge approach.
Mid: Implements the partition search with sentinels and explains why the conditions are monotonic. Explains the role of the infinity sentinels.
Senior: Generalises to k-th smallest, compares with streaming median using two heaps, and proves the bound on iterations. Can explain why the shorter list must be the one searched.
Key points
Binary search the number taken from the shorter list
j = half - i fills the left part
Valid cut: a_left <= b_right and b_left <= a_right
Use infinities past the ends
O(log(min(m, n)))
Common mistakes
Searching the longer list so j goes negative
Forgetting the empty-side cases
Wrong median formula for odd totals
Integer division where a float median is expected
Follow-ups
How would you find the k-th smallest of two sorted arrays?
What about the median of k sorted arrays?
How would you maintain a running median of a stream?
Tips
Start from the merge solution and its cost
Draw the cut on both lists
State the two cross conditions clearly
Evaluation rubric
Correct partition logic
Handles empty and boundary cuts
Correct odd and even formulas
Correct complexity
33.algorithms-0033Hardsenior
Longest increasing subsequence: find the length of the longest strictly increasing subsequence in O(n log n).
The O(n^2) DP sets best[i] = 1 + max(best[j]) over earlier smaller values. The O(n log n) method keeps tails[k], the smallest possible last value of an increasing subsequence of length k + 1. For each value, binary search the first tail at least as large and replace it, or append if none exists. The length of tails is the answer; tails itself is not necessarily a real subsequence.
Full answer
Problem
Given nums, return the length of the longest strictly increasing subsequence (not necessarily contiguous).
Example: [10, 9, 2, 5, 3, 7, 101, 18] gives 4 ([2, 3, 7, 18] is one answer).
Constraints: 0 <= len(nums) <= 2500 (the O(n log n) method scales to 10^5 and more).
Brute force
Try all 2^n subsequences: exponential.
Better: O(n^2) DP
best[i] = length of the longest increasing subsequence ending at i = 1 + max(best[j] for j < i if nums[j] < nums[i]), or 1. The answer is max(best). This is easy to explain and is the reference in the test.
Optimal approach
Keep tails, where tails[k] is the smallest tail of any increasing subsequence of length k + 1 found so far. For each x:
i = bisect_left(tails, x), the first tail at least x.
If i == len(tails), append x (a longer subsequence exists).
Otherwise set tails[i] = x (a length i + 1 subsequence can now end lower).
Why it works
tails is always strictly increasing: a subsequence of length k + 1 contains one of length k with a smaller tail. A smaller tail is never worse, because it leaves more room for future values. When x arrives, it can extend every subsequence whose tail is less than x; the longest of those has length i, so x becomes the best tail for length i + 1. Using bisect_left makes the subsequence strictly increasing; bisect_right would allow equal values (non-decreasing).
The final tails is not always an actual subsequence. To reconstruct one, also store, for each position, the index of its predecessor.
Complexity
O(n log n) time, O(n) space. The DP version is O(n^2) time.
Code
python
from bisect import bisect_left
def length_of_lis(nums):
"""Length of the longest strictly increasing subsequence. O(n log n).
tails[k] = smallest possible tail of an increasing subsequence of length k + 1.
"""
tails = []
for x in nums:
i = bisect_left(tails, x) # first tail >= x
if i == len(tails):
tails.append(x) # x extends the longest subsequence
else:
tails[i] = x # x is a smaller tail for length i + 1
return len(tails)
def length_of_lis_dp(nums):
"""O(n^2) dynamic programming reference."""
best = [1] * len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[j] < nums[i]:
best[i] = max(best[i], best[j] + 1)
return max(best, default=0)
if __name__ == "__main__":
for f in (length_of_lis, length_of_lis_dp):
assert f([10, 9, 2, 5, 3, 7, 101, 18]) == 4
assert f([0, 1, 0, 3, 2, 3]) == 4
assert f([7, 7, 7, 7]) == 1 # strictly increasing
assert f([]) == 0
assert f([5]) == 1
assert f([1, 2, 3, 4]) == 4
assert f([4, 3, 2, 1]) == 1
print("all tests passed")
Save as a33_lis.py and run python3 a33_lis.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty list returns 0. All equal values returns 1 (strictly increasing). Already sorted returns n. Strictly decreasing returns 1. Negative numbers work the same way.
Pattern
DP with a monotonic auxiliary array searched by binary search (patience sorting). Related: Russian doll envelopes (sort, then LIS), longest chain of pairs, and minimum deletions to make a list sorted.
python
from bisect import bisect_left
def length_of_lis(nums):
"""Length of the longest strictly increasing subsequence. O(n log n).
tails[k] = smallest possible tail of an increasing subsequence of length k + 1.
"""
tails = []
for x in nums:
i = bisect_left(tails, x) # first tail >= x
if i == len(tails):
tails.append(x) # x extends the longest subsequence
else:
tails[i] = x # x is a smaller tail for length i + 1
return len(tails)
def length_of_lis_dp(nums):
"""O(n^2) dynamic programming reference."""
best = [1] * len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[j] < nums[i]:
best[i] = max(best[i], best[j] + 1)
return max(best, default=0)
if __name__ == "__main__":
for f in (length_of_lis, length_of_lis_dp):
assert f([10, 9, 2, 5, 3, 7, 101, 18]) == 4
assert f([0, 1, 0, 3, 2, 3]) == 4
assert f([7, 7, 7, 7]) == 1 # strictly increasing
assert f([]) == 0
assert f([5]) == 1
assert f([1, 2, 3, 4]) == 4
assert f([4, 3, 2, 1]) == 1
print("all tests passed")
tails array with bisect_left plus an O(n^2) DP reference; both pass the same tests.
Complexity
Time: O(n log n). Space: O(n). The DP version is O(n^2) and is used as a reference.
By level
Fresher: Writes the O(n^2) DP with the recurrence and traces the example. Should test a list of equal values.
Mid: Implements the tails method, explains why tails stays sorted and handles strictness. Explains the choice between bisect_left and bisect_right.
Senior: Reconstructs the sequence with predecessor links, solves envelope variants and relates it to patience sorting and the Erdos-Szekeres bound. Explains how to rebuild the actual subsequence.
Key points
tails[k] is the smallest tail of a length k + 1 increasing subsequence
tails stays sorted, so binary search works
Replace the first tail >= x, or append
bisect_left for strict, bisect_right for non-decreasing
tails is not the subsequence itself
Common mistakes
Returning tails as the answer subsequence
Using bisect_right for a strictly increasing requirement
Confusing subsequence with subarray
Not explaining why a smaller tail is better
Follow-ups
How would you reconstruct the subsequence?
How do you solve Russian doll envelopes?
What changes for non-decreasing subsequences?
Tips
Give the O(n^2) DP first
Explain the tails invariant in one sentence
Test equal values
Evaluation rubric
Correct DP recurrence
Correct O(n log n) method
Strict versus non-strict handled
Correct complexity
34.algorithms-0034Easyfresher
Implement a stack with push, pop and peek, and extend it into a min stack that returns the current minimum in O(1).
A stack is last in, first out; a Python list gives O(1) amortised push and pop at the end. pop and peek on an empty stack should raise an error, not return a special string that callers might treat as data. A min stack stores each value with the minimum at that point, so get_min reads the top pair in O(1).
Full answer
Problem
Implement Stack with push(x), pop(), peek(), is_empty() and len(). Then implement MinStack with the same operations plus get_min(), all O(1).
Example: push 5, 3, 7, 3, 1: get_min() is 1. Pop once: get_min() is 3. Pop until only 5 is left: get_min() is 5.
Constraints: up to 10^5 operations; values can repeat. Operations on an empty stack raise IndexError.
Brute force
For get_min, scan the whole stack: O(n) per call. Rebuilding the minimum after every pop is also O(n).
Optimal approach
Stack:
Back it with a list; append and pop() work at the end in O(1) amortised.
Raise IndexError for pop or peek on an empty stack. Returning a string such as "Stack is empty" mixes error signals with real values: a stack of strings could legitimately contain that text.
MinStack:
Push (value, min(value, current_min)).
get_min returns the second field of the top pair.
pop removes the pair, which automatically restores the previous minimum.
Why it works
Every stack state is a prefix of the push history. The minimum of a prefix never depends on later elements, so storing it alongside each element records the minimum of every possible state. Popping returns to an earlier prefix whose minimum is already stored.
A memory-saving variant keeps a second stack holding only new minimums (push when x <= current_min, pop when the popped value equals it). The <= handles repeated minimum values.
Complexity
All operations O(1) time (amortised for list growth). Space O(n); the pair version stores two values per element.
Code
python
class Stack:
"""LIFO stack backed by a Python list. push/pop/peek are O(1) amortised."""
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if not self._items:
raise IndexError("pop from empty stack") # raise, do not return a string
return self._items.pop()
def peek(self):
if not self._items:
raise IndexError("peek from empty stack")
return self._items[-1]
def is_empty(self):
return not self._items
def __len__(self):
return len(self._items)
class MinStack(Stack):
"""Stack that also returns its minimum in O(1) by storing (value, min_so_far)."""
def push(self, item):
current_min = item if self.is_empty() else min(item, self._items[-1][1])
self._items.append((item, current_min))
def pop(self):
return super().pop()[0]
def peek(self):
return super().peek()[0]
def get_min(self):
if self.is_empty():
raise IndexError("min of empty stack")
return self._items[-1][1]
if __name__ == "__main__":
s = Stack()
assert s.is_empty() and len(s) == 0
s.push("maths")
s.push("physics")
assert s.peek() == "physics" and len(s) == 2
assert s.pop() == "physics" and s.pop() == "maths"
for op in (s.pop, s.peek):
try:
op()
raise AssertionError("expected IndexError")
except IndexError:
pass
m = MinStack()
for x in (5, 3, 7, 3, 1):
m.push(x)
assert m.get_min() == 1
m.pop()
assert m.get_min() == 3
m.pop()
m.pop()
assert m.get_min() == 3 and m.peek() == 3
m.pop()
assert m.get_min() == 5
print("all tests passed")
Save as a34_stack.py and run python3 a34_stack.py. It prints all tests passed (Python 3.13.5).
Edge cases
Pop, peek or get_min on an empty stack raise IndexError. Repeated minimum values (5, 3, 7, 3 then pop one 3: minimum is still 3). Mixed types should be avoided in MinStack because min compares them.
Pattern
Stack (LIFO) and augmenting a data structure with extra per-element information. Stacks power undo history, function calls, bracket matching, expression evaluation and the monotonic stack problems.
python
class Stack:
"""LIFO stack backed by a Python list. push/pop/peek are O(1) amortised."""
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if not self._items:
raise IndexError("pop from empty stack") # raise, do not return a string
return self._items.pop()
def peek(self):
if not self._items:
raise IndexError("peek from empty stack")
return self._items[-1]
def is_empty(self):
return not self._items
def __len__(self):
return len(self._items)
class MinStack(Stack):
"""Stack that also returns its minimum in O(1) by storing (value, min_so_far)."""
def push(self, item):
current_min = item if self.is_empty() else min(item, self._items[-1][1])
self._items.append((item, current_min))
def pop(self):
return super().pop()[0]
def peek(self):
return super().peek()[0]
def get_min(self):
if self.is_empty():
raise IndexError("min of empty stack")
return self._items[-1][1]
if __name__ == "__main__":
s = Stack()
assert s.is_empty() and len(s) == 0
s.push("maths")
s.push("physics")
assert s.peek() == "physics" and len(s) == 2
assert s.pop() == "physics" and s.pop() == "maths"
for op in (s.pop, s.peek):
try:
op()
raise AssertionError("expected IndexError")
except IndexError:
pass
m = MinStack()
for x in (5, 3, 7, 3, 1):
m.push(x)
assert m.get_min() == 1
m.pop()
assert m.get_min() == 3
m.pop()
m.pop()
assert m.get_min() == 3 and m.peek() == 3
m.pop()
assert m.get_min() == 5
print("all tests passed")
List-backed Stack that raises IndexError on empty access; MinStack stores (value, min so far) pairs.
Complexity
Time: O(1) per operation (amortised for push). Space: O(n). The two-stack variant uses less memory when the minimum rarely changes.
By level
Fresher: Implements the list-backed stack with IndexError on empty access and gives everyday uses such as undo. Should state the cost of each operation.
Mid: Builds the min stack with pairs or a second stack, handles duplicate minimums and explains the prefix argument. Handles repeated minimum values.
Senior: Discusses memory trade-offs between variants, thread safety, and extends the idea to min queues built from two min stacks. Can explain the memory cost of the pair version against the two-stack version.
Key points
Stack is last in, first out
Use the end of a Python list for O(1) push and pop
Raise IndexError on empty pop or peek
Min stack stores the minimum at each level
Popping restores the previous minimum for free
Common mistakes
Returning an error string instead of raising
Pushing and popping at the front of a list (O(n))
Recomputing the minimum after each pop
Using < instead of <= in the two-stack min variant
Follow-ups
How would you add get_max?
Can you implement a stack with queues?
How would you build a min queue?
Tips
Name LIFO and a real example such as undo
Explain why raising is better than a sentinel string
Trace the min stack with a repeated minimum
Evaluation rubric
Correct LIFO operations
Correct empty handling
O(1) get_min with correct justification
Clear code
35.algorithms-0035Easyfresher
Implement a FIFO queue with O(1) enqueue and dequeue, and then build the same queue using only two stacks.
A queue is first in, first out. list.pop(0) is O(n) because every element shifts, so use collections.deque, whose popleft is O(1). With two stacks, push onto an inbox stack; when the outbox is empty, move everything across, which reverses the order. Each element moves at most once, so dequeue is amortised O(1).
Full answer
Problem
Implement Queue with enqueue(x), dequeue(), peek() and len(), all O(1). Then implement QueueFromStacks using only two Python lists used as stacks (append and pop at the end).
Example: a ticket counter: enqueue T1, T2, T3; dequeue gives T1; enqueue T4; the next three dequeues give T2, T3, T4.
Constraints: up to 10^5 operations; dequeue on an empty queue raises IndexError.
Brute force
A Python list with append and pop(0). Correct, but pop(0) shifts all remaining elements, so it is O(n) per dequeue and O(n^2) for n operations.
Optimal approach
Queue: back it with collections.deque; append adds to the back and popleft removes from the front, both O(1).
QueueFromStacks:
enqueue pushes onto in_stack.
dequeue: if out_stack is empty, pop everything from in_stack and push it onto out_stack, reversing the order. Then pop from out_stack.
Raise IndexError if both stacks are empty.
Why it works
Reversing a stack once turns its last-in order into first-in order. Elements in out_stack are always older than elements in in_stack, so serving out_stack first keeps FIFO order. Moving only when out_stack is empty preserves that property.
Amortised cost: each element is pushed onto in_stack once, moved once and popped from out_stack once, so n operations cost O(n) total, even though a single dequeue can cost O(n).
Complexity
Deque version: O(1) per operation. Two-stack version: O(1) amortised, O(n) worst case for one dequeue. Both O(n) space.
Code
python
from collections import deque
class Queue:
"""FIFO queue backed by collections.deque: enqueue and dequeue are O(1)."""
def __init__(self):
self._items = deque()
def enqueue(self, item):
self._items.append(item)
def dequeue(self):
if not self._items:
raise IndexError("dequeue from empty queue")
return self._items.popleft()
def peek(self):
if not self._items:
raise IndexError("peek from empty queue")
return self._items[0]
def __len__(self):
return len(self._items)
class QueueFromStacks:
"""Queue built from two stacks; each element moves at most once: amortised O(1)."""
def __init__(self):
self._in, self._out = [], []
def enqueue(self, item):
self._in.append(item)
def dequeue(self):
if not self._out:
while self._in:
self._out.append(self._in.pop()) # reverse order once
if not self._out:
raise IndexError("dequeue from empty queue")
return self._out.pop()
def __len__(self):
return len(self._in) + len(self._out)
if __name__ == "__main__":
for Q in (Queue, QueueFromStacks):
q = Q()
for token in ("T1", "T2", "T3"):
q.enqueue(token)
assert q.dequeue() == "T1"
q.enqueue("T4")
assert [q.dequeue() for _ in range(3)] == ["T2", "T3", "T4"]
assert len(q) == 0
try:
q.dequeue()
raise AssertionError("expected IndexError")
except IndexError:
pass
q = Queue()
q.enqueue(1)
assert q.peek() == 1 and len(q) == 1
print("all tests passed")
Save as a35_queue.py and run python3 a35_queue.py. It prints all tests passed (Python 3.13.5).
Edge cases
Dequeue or peek on an empty queue raise IndexError. Interleaved enqueues and dequeues (the test enqueues T4 after a dequeue). Moving elements while out_stack still has items would break the order.
Pattern
Queue (FIFO) and amortised analysis. Queues drive breadth-first search, task scheduling and buffering; the two-stack trick also builds a min queue from two min stacks.
python
from collections import deque
class Queue:
"""FIFO queue backed by collections.deque: enqueue and dequeue are O(1)."""
def __init__(self):
self._items = deque()
def enqueue(self, item):
self._items.append(item)
def dequeue(self):
if not self._items:
raise IndexError("dequeue from empty queue")
return self._items.popleft()
def peek(self):
if not self._items:
raise IndexError("peek from empty queue")
return self._items[0]
def __len__(self):
return len(self._items)
class QueueFromStacks:
"""Queue built from two stacks; each element moves at most once: amortised O(1)."""
def __init__(self):
self._in, self._out = [], []
def enqueue(self, item):
self._in.append(item)
def dequeue(self):
if not self._out:
while self._in:
self._out.append(self._in.pop()) # reverse order once
if not self._out:
raise IndexError("dequeue from empty queue")
return self._out.pop()
def __len__(self):
return len(self._in) + len(self._out)
if __name__ == "__main__":
for Q in (Queue, QueueFromStacks):
q = Q()
for token in ("T1", "T2", "T3"):
q.enqueue(token)
assert q.dequeue() == "T1"
q.enqueue("T4")
assert [q.dequeue() for _ in range(3)] == ["T2", "T3", "T4"]
assert len(q) == 0
try:
q.dequeue()
raise AssertionError("expected IndexError")
except IndexError:
pass
q = Queue()
q.enqueue(1)
assert q.peek() == 1 and len(q) == 1
print("all tests passed")
Queue on collections.deque and QueueFromStacks with lazy transfer; both pass the same FIFO tests.
Complexity
Time: O(1) per operation; two-stack dequeue is O(1) amortised, O(n) worst case. Space: O(n). Each element is moved between the stacks at most once.
By level
Fresher: Implements the deque queue, explains why list.pop(0) is slow and traces the ticket example. Should test interleaved enqueue and dequeue calls.
Mid: Implements the two-stack queue with lazy transfer and gives the amortised argument. Explains the difference between amortised and worst-case cost.
Senior: Discusses worst-case latency of the two-stack queue, ring buffers, bounded queues with backpressure and thread-safe options such as queue.Queue. Can explain when one slow dequeue in the two-stack version matters for latency.
Key points
Queue is first in, first out
list.pop(0) is O(n); deque.popleft is O(1)
Two stacks: move only when the outbox is empty
Each element moves once: amortised O(1)
Raise on empty dequeue
Common mistakes
Using list.pop(0) in a hot loop
Transferring on every dequeue
Moving elements while the outbox is non-empty
Confusing amortised with worst-case time
Follow-ups
How would you implement a stack with queues?
How would you build a circular buffer of fixed size?
Where do queues appear in graph algorithms?
Tips
Say why pop(0) is slow
Explain the reversal step with a small trace
Define amortised cost clearly
Evaluation rubric
Correct FIFO behaviour
O(1) operations with deque
Correct two-stack logic
Correct amortised analysis
36.algorithms-0036Easyfresher
Valid parentheses: check whether every bracket in a string is closed by the same type in the correct order.
Push each opening bracket onto a stack. On a closing bracket, the stack must be non-empty and its top must be the matching opener; pop it. At the end the stack must be empty. A counter works for one bracket type but fails for mixed types such as "([)]", which is why a stack is needed. O(n) time.
Full answer
Problem
Given a string containing ()[]{} and possibly other characters, return True if brackets are balanced and properly nested.
Example: "{[]}" is valid, "([)]" is not, "f(a[i]) + {x}" is valid (other characters are ignored).
Constraints: 0 <= len(s) <= 10^4.
Brute force
Repeatedly delete adjacent pairs "()", "[]", "{}" until nothing changes; valid if the string ends empty. O(n^2) in the worst case.
Optimal approach
Map each closer to its opener: {")": "(", "]": "[", "}": "{"}.
For each character: push openers; for a closer, return False if the stack is empty or the popped opener does not match.
Return True only if the stack is empty at the end.
Why it works
Proper nesting means the most recently opened bracket must close first, which is exactly last in, first out. The stack holds unmatched openers in order; each closer must match the latest one. Leftover openers at the end were never closed.
A single counter works only for one type: it accepts "([)]" because the counts balance, even though the order is wrong.
Complexity
O(n) time, O(n) space in the worst case (all openers).
Code
python
def is_valid(s):
"""True if every bracket is closed by the same type in the right order. O(n)."""
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
# other characters are ignored
return not stack
if __name__ == "__main__":
assert is_valid("()") is True
assert is_valid("()[]{}") is True
assert is_valid("(]") is False
assert is_valid("([)]") is False
assert is_valid("{[]}") is True
assert is_valid("") is True
assert is_valid("(") is False
assert is_valid(")") is False
assert is_valid("f(a[i]) + {x}") is True
print("all tests passed")
Save as a36_valid_parentheses.py and run python3 a36_valid_parentheses.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty string is valid. A lone closer (")") is invalid because the stack is empty. A lone opener is invalid because the stack is not empty at the end. Non-bracket characters are skipped. Odd length containing only brackets can be rejected early as an optimisation.
Pattern
Stack for matching nested structure. Related: minimum additions to make brackets valid, longest valid parentheses, evaluating expressions, HTML or XML tag matching, and checking balanced code blocks in editors.
python
def is_valid(s):
"""True if every bracket is closed by the same type in the right order. O(n)."""
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
# other characters are ignored
return not stack
if __name__ == "__main__":
assert is_valid("()") is True
assert is_valid("()[]{}") is True
assert is_valid("(]") is False
assert is_valid("([)]") is False
assert is_valid("{[]}") is True
assert is_valid("") is True
assert is_valid("(") is False
assert is_valid(")") is False
assert is_valid("f(a[i]) + {x}") is True
print("all tests passed")
Stack with a closer-to-opener map; ignores non-bracket characters.
Complexity
Time: O(n). Space: O(n). The repeated-deletion brute force is O(n^2).
By level
Fresher: Explains last in, first out matching, writes the stack solution and tests the main invalid cases. Should test a lone opener and a lone closer.
Mid: Explains why counters fail for mixed types and extends to reporting error positions. Reports the index of the first error.
Senior: Connects to parsing and grammars, handles very long inputs or streaming, and solves the longest valid parentheses variant. Can explain how the same method checks nested tags in markup.
Key points
Push openers, match closers against the top
Empty stack on a closer means invalid
Leftover openers mean invalid
A counter fails for mixed bracket types
O(n) time
Common mistakes
Using one counter for all bracket types
Popping without checking for an empty stack
Forgetting to check the stack is empty at the end
Treating other characters as errors without stating the rule
Follow-ups
What is the minimum number of insertions to make a string valid?
How would you find the longest valid parentheses substring?
How would you report the position of the first error?
Tips
Give the "([)]" counterexample for a counter
State the map from closers to openers
Test a lone closer and a lone opener
Evaluation rubric
Correct stack logic
Handles empty and unbalanced cases
Correct complexity
Explains why a stack is needed
37.algorithms-0037Mediummid
Daily temperatures: for each day, find how many days until a warmer temperature, using a monotonic stack.
Keep a stack of indices whose temperatures are still waiting for a warmer day, in decreasing order of temperature. When a warmer day arrives, pop every colder index and record the distance. Each index is pushed and popped once, so the whole scan is O(n) instead of O(n^2) for scanning forward from each day.
Full answer
Problem
Given daily temperatures, return a list where answer[i] is the number of days after day i until a strictly warmer temperature, or 0 if there is none.
Constraints: 1 <= len(temps) <= 10^5, values between 30 and 100.
Brute force
For each day, scan forward until a warmer day: O(n^2) in the worst case, for example a long run of decreasing temperatures followed by one hot day.
Optimal approach
Stack of indices with decreasing temperatures.
For each day i:
While the stack is not empty and temps[stack[-1]] < temps[i]: pop j and set answer[j] = i - j.
Push i.
Indices left on the stack at the end keep 0.
Why it works
Day i is the first warmer day for exactly those waiting days that are colder than it, and those are on top of the stack because waiting days are stored with decreasing temperatures. If the top is not colder, nothing below it is colder either, so the loop can stop. Each day is popped at the moment its first warmer day appears, which is the definition of the answer.
Complexity
O(n) time: each index is pushed once and popped at most once. O(n) space for the stack in the worst case (decreasing temperatures).
Code
python
def daily_temperatures(temps):
"""For each day, how many days until a warmer one (0 if none). Monotonic stack, O(n)."""
answer = [0] * len(temps)
stack = [] # indices whose temperatures are decreasing
for i, t in enumerate(temps):
while stack and temps[stack[-1]] < t:
j = stack.pop()
answer[j] = i - j # day i is the first warmer day after j
stack.append(i)
return answer
def brute(temps):
n = len(temps)
out = []
for i in range(n):
out.append(next((j - i for j in range(i + 1, n) if temps[j] > temps[i]), 0))
return out
if __name__ == "__main__":
for f in (daily_temperatures, brute):
assert f([73, 74, 75, 71, 69, 72, 76, 73]) == [1, 1, 4, 2, 1, 1, 0, 0]
assert f([30, 40, 50, 60]) == [1, 1, 1, 0]
assert f([30, 60, 90]) == [1, 1, 0]
assert f([50, 50, 50]) == [0, 0, 0]
assert f([]) == []
print("all tests passed")
Save as a37_daily_temperatures.py and run python3 a37_daily_temperatures.py. It prints all tests passed (Python 3.13.5).
Edge cases
Equal temperatures do not count as warmer (< in the pop condition, so [50, 50, 50] gives all zeros). Strictly increasing input gives all 1s except the last. Strictly decreasing input leaves every index on the stack. Empty input returns an empty list.
Pattern
Monotonic stack for "next greater element". Variants: next smaller element (flip the comparison), previous greater element (scan from the other side), stock span, and the circular version (scan the list twice).
python
def daily_temperatures(temps):
"""For each day, how many days until a warmer one (0 if none). Monotonic stack, O(n)."""
answer = [0] * len(temps)
stack = [] # indices whose temperatures are decreasing
for i, t in enumerate(temps):
while stack and temps[stack[-1]] < t:
j = stack.pop()
answer[j] = i - j # day i is the first warmer day after j
stack.append(i)
return answer
def brute(temps):
n = len(temps)
out = []
for i in range(n):
out.append(next((j - i for j in range(i + 1, n) if temps[j] > temps[i]), 0))
return out
if __name__ == "__main__":
for f in (daily_temperatures, brute):
assert f([73, 74, 75, 71, 69, 72, 76, 73]) == [1, 1, 4, 2, 1, 1, 0, 0]
assert f([30, 40, 50, 60]) == [1, 1, 1, 0]
assert f([30, 60, 90]) == [1, 1, 0]
assert f([50, 50, 50]) == [0, 0, 0]
assert f([]) == []
print("all tests passed")
Decreasing stack of indices; an O(n^2) forward-scan reference passes the same tests.
Complexity
Time: O(n). Space: O(n). Amortised: every index is pushed once and popped at most once.
By level
Fresher: Explains the brute force and the waiting-days idea, then writes the stack solution with indices. Should explain why each index is popped at most once.
Mid: Gives the amortised O(n) proof and adapts it to next smaller or previous greater variants. Handles equal temperatures correctly.
Senior: Generalises monotonic stacks to histogram, sum of subarray minimums and circular variants, and discusses offline versus streaming use. Solves the circular next greater element variant.
Key points
Stack holds indices still waiting for a warmer day
Pop while the top is colder than today
Distance is i - j at the moment of popping
Each index is pushed and popped once: O(n)
Strictly warmer means < in the pop condition
Common mistakes
Storing temperatures instead of indices
Using <= and treating equal days as warmer
Claiming O(n^2) because of the nested while loop
Forgetting that unresolved days stay 0
Follow-ups
How would you solve next greater element on a circular list?
How would you compute the stock span?
How do you find the previous smaller element?
Tips
Explain "waiting days" in plain words
Give the amortised argument for the inner loop
Test equal temperatures
Evaluation rubric
Correct monotonic stack
Correct amortised analysis
Handles equal values and unresolved days
Clear explanation
38.algorithms-0038Hardsenior
Largest rectangle in a histogram: find the area of the largest rectangle that fits under a bar chart of unit-width bars.
For each bar, the widest rectangle using its full height stretches until the nearest shorter bar on each side. Keep a stack of indices with increasing heights; when a shorter bar arrives, pop taller bars, because the arriving bar is their right limit and the new top of the stack is their left limit. A sentinel 0 at the end flushes the stack. O(n) time.
Full answer
Problem
Given bar heights, each bar width 1, return the largest rectangle area within the histogram.
For every pair (i, j), the rectangle height is the minimum bar in between; keep a running minimum as j grows: O(n^2). The test uses this as the reference.
Optimal approach
Scan heights + [0] with a stack of indices whose heights increase.
For each i with height h:
While the top bar is at least as tall as h: pop top.
Its right limit is i (the first shorter bar to the right).
Its left limit is the new stack top plus 1, or 0 if the stack is empty.
Area is heights[top] x (i - left).
Push i.
The final 0 is shorter than every bar, so it pops everything that remains.
Why it works
The largest rectangle has some bar as its shortest bar, and for that bar the best rectangle extends to the nearest strictly shorter bar on each side. The increasing stack means the element below top is the nearest bar to the left that is shorter (or equal, which is fine, since an equal bar to the left will produce the full-width rectangle when it is popped later). The bar that causes the pop is the first one to the right that is not taller. So every bar's maximal rectangle is computed when it is popped.
Complexity
O(n) time: each index is pushed and popped once. O(n) space.
Code
python
def largest_rectangle(heights):
"""Largest rectangle in a histogram using a monotonic increasing stack. O(n)."""
stack = [] # indices with increasing heights
best = 0
for i, h in enumerate(heights + [0]): # sentinel 0 flushes the stack
while stack and heights[stack[-1]] >= h:
top = stack.pop()
left = stack[-1] + 1 if stack else 0 # first bar not shorter, to the left
width = i - left
best = max(best, heights[top] * width)
stack.append(i)
return best
def brute(heights):
best = 0
for i in range(len(heights)):
low = heights[i]
for j in range(i, len(heights)):
low = min(low, heights[j])
best = max(best, low * (j - i + 1))
return best
if __name__ == "__main__":
for f in (largest_rectangle, brute):
assert f([2, 1, 5, 6, 2, 3]) == 10
assert f([2, 4]) == 4
assert f([]) == 0
assert f([0]) == 0
assert f([3, 3, 3]) == 9
assert f([6, 2, 5, 4, 5, 1, 6]) == 12
print("all tests passed")
Save as a38_histogram.py and run python3 a38_histogram.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty list returns 0. Bars of height 0 split the histogram. All equal heights give h x n. Strictly increasing heights are all handled by the sentinel. Concatenating [0] creates a new list; the code uses it only for iteration and still reads heights[top] from the original.
Pattern
Monotonic stack for nearest smaller element on both sides. The maximal rectangle of 1s in a binary matrix applies this row by row. Related: sum of subarray minimums and trapping rain water with a stack.
python
def largest_rectangle(heights):
"""Largest rectangle in a histogram using a monotonic increasing stack. O(n)."""
stack = [] # indices with increasing heights
best = 0
for i, h in enumerate(heights + [0]): # sentinel 0 flushes the stack
while stack and heights[stack[-1]] >= h:
top = stack.pop()
left = stack[-1] + 1 if stack else 0 # first bar not shorter, to the left
width = i - left
best = max(best, heights[top] * width)
stack.append(i)
return best
def brute(heights):
best = 0
for i in range(len(heights)):
low = heights[i]
for j in range(i, len(heights)):
low = min(low, heights[j])
best = max(best, low * (j - i + 1))
return best
if __name__ == "__main__":
for f in (largest_rectangle, brute):
assert f([2, 1, 5, 6, 2, 3]) == 10
assert f([2, 4]) == 4
assert f([]) == 0
assert f([0]) == 0
assert f([3, 3, 3]) == 9
assert f([6, 2, 5, 4, 5, 1, 6]) == 12
print("all tests passed")
Increasing stack with a 0 sentinel; an O(n^2) running-minimum reference passes the same tests.
Complexity
Time: O(n). Space: O(n). Each bar's area is computed once, when it is popped.
By level
Fresher: Gives the O(n^2) solution and explains the idea of extending each bar to the nearest shorter bars. Should give the O(n^2) running-minimum solution.
Mid: Implements the stack version with correct width formula and sentinel, and handles equal heights. Explains the sentinel at the end.
Senior: Solves the matrix version, compares with the two-pass left and right arrays approach, and generalises the nearest-smaller pattern. Applies the method to the binary matrix problem.
Key points
Each bar's best rectangle extends to the nearest shorter bars
Increasing stack gives the left limit
The bar causing the pop is the right limit
Sentinel 0 flushes remaining bars
O(n) time
Common mistakes
Computing width with the popped index instead of the new stack top
Forgetting to flush the stack at the end
Mishandling equal heights without reasoning about them
Assuming the rectangle must start at a bar's own index
Follow-ups
How do you find the maximal rectangle of 1s in a binary matrix?
How would you compute the sum of minimums of all subarrays?
Can you do it with precomputed left and right smaller arrays?
Tips
Explain "each bar as the shortest" first
Draw the stack on the example
Explain the sentinel
Evaluation rubric
Correct stack algorithm and widths
Correct handling of ends and equal heights
Correct complexity
Clear justification
39.algorithms-0039Easyfresher
Reverse a singly linked list in place, both iteratively and recursively.
Walk the list with three references: prev, current and the saved next. Point current.next back at prev, then move all three forward. When current becomes None, prev is the new head. This is O(n) time and O(1) extra space; the recursive version is also O(n) but uses O(n) call stack.
Full answer
Problem
Given the head of a singly linked list, reverse it and return the new head.
Copy the values into a Python list, reverse it, and build a new list (or write the values back). O(n) time but O(n) extra space, and it does not show pointer handling, which is what the question tests.
Optimal approach
Iterative:
prev = None.
While head: nxt = head.next; head.next = prev; prev = head; head = nxt.
Invariant for the iterative loop: prev is the head of the already reversed prefix, and head is the head of the untouched remainder. Each step moves one node from the remainder to the front of the reversed part. Saving nxt first is essential; otherwise the rest of the list is lost when head.next is overwritten.
In the recursive version, after the call, head.next is the tail of the reversed rest, so setting its next to head appends head at the end.
Complexity
O(n) time for both. Iterative O(1) extra space; recursive O(n) stack, which hits Python's default recursion limit (about 1000) on long lists.
Code
python
class ListNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
def from_list(values):
head = None
for v in reversed(values):
head = ListNode(v, head)
return head
def to_list(head):
out = []
while head:
out.append(head.val)
head = head.next
return out
def reverse_list(head):
"""Reverse a singly linked list iteratively. O(n) time, O(1) extra space."""
prev = None
while head:
nxt = head.next # save the rest of the list
head.next = prev # point this node backwards
prev = head
head = nxt
return prev
def reverse_list_recursive(head):
"""O(n) time, O(n) call stack."""
if head is None or head.next is None:
return head
new_head = reverse_list_recursive(head.next)
head.next.next = head
head.next = None
return new_head
if __name__ == "__main__":
for f in (reverse_list, reverse_list_recursive):
assert to_list(f(from_list([1, 2, 3, 4, 5]))) == [5, 4, 3, 2, 1]
assert to_list(f(from_list([1, 2]))) == [2, 1]
assert to_list(f(from_list([7]))) == [7]
assert f(None) is None
print("all tests passed")
Save as a39_reverse_linked_list.py and run python3 a39_reverse_linked_list.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty list returns None. A single node returns itself. Two nodes test the pointer swap. Forgetting head.next = None in the recursive version creates a cycle between the first two nodes.
Pattern
Pointer rewiring with a saved next pointer. Building blocks for reversing a sublist between positions m and n, reversing in groups of k, checking a palindrome list, and adding numbers stored as lists.
python
class ListNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
def from_list(values):
head = None
for v in reversed(values):
head = ListNode(v, head)
return head
def to_list(head):
out = []
while head:
out.append(head.val)
head = head.next
return out
def reverse_list(head):
"""Reverse a singly linked list iteratively. O(n) time, O(1) extra space."""
prev = None
while head:
nxt = head.next # save the rest of the list
head.next = prev # point this node backwards
prev = head
head = nxt
return prev
def reverse_list_recursive(head):
"""O(n) time, O(n) call stack."""
if head is None or head.next is None:
return head
new_head = reverse_list_recursive(head.next)
head.next.next = head
head.next = None
return new_head
if __name__ == "__main__":
for f in (reverse_list, reverse_list_recursive):
assert to_list(f(from_list([1, 2, 3, 4, 5]))) == [5, 4, 3, 2, 1]
assert to_list(f(from_list([1, 2]))) == [2, 1]
assert to_list(f(from_list([7]))) == [7]
assert f(None) is None
print("all tests passed")
Iterative and recursive reversal with list helpers; both pass the same tests, including the empty list.
Complexity
Time: O(n). Space: O(1) iterative; O(n) recursive call stack. The recursive version is limited by Python's recursion depth on long lists.
By level
Fresher: Writes the iterative three-pointer reversal and traces it on a short list. Should test the empty list and a single node.
Mid: Gives both versions, states the invariant and explains the recursion depth limit in Python. Explains why next must be saved before rewiring.
Senior: Extends to sublist and k-group reversal, discusses immutable list designs and memory safety when rewiring pointers. Explains the risk of deep recursion in Python.
Key points
Save next before rewiring
prev is the head of the reversed part
Return prev at the end
Iterative uses O(1) space
Recursive uses O(n) stack
Common mistakes
Losing the rest of the list by overwriting next first
Returning the old head
Creating a cycle by not clearing head.next in recursion
Copying values into a list when in-place is asked
Follow-ups
How would you reverse only positions m to n?
How do you reverse in groups of k?
How would you check whether a linked list is a palindrome?
Tips
Draw three boxes for prev, current and next
State the loop invariant
Test empty, one and two nodes
Evaluation rubric
Correct in-place reversal
Correct return value
Handles empty and single-node lists
Correct space analysis
40.algorithms-0040Mediumfresher
Detect a cycle in a linked list and return the node where the cycle begins, using O(1) extra space.
Move a slow pointer one step and a fast pointer two steps. If fast reaches the end, there is no cycle; if they meet, there is one. To find the start, reset one pointer to the head and move both one step at a time; they meet at the cycle's first node. O(n) time and O(1) space, versus O(n) space for a visited set.
Full answer
Problem
Given the head of a singly linked list, return the node where a cycle begins, or None if there is no cycle. Do not modify the list.
Example: 3 -> 2 -> 0 -> -4, with -4 linking back to 2: return the node with value 2.
Constraints: 0 <= n <= 10^4 nodes. Return the node object, not its value (values may repeat).
Brute force
Store visited nodes in a set; the first node seen twice is the cycle start. O(n) time, O(n) space. The test uses this as the reference.
Optimal approach
slow = fast = head.
While fast and fast.next: slow = slow.next, fast = fast.next.next; if slow is fast, a cycle exists.
Set slow = head; move slow and fast one step at a time until they meet; return that node.
If the loop ends, return None.
Why it works
Detection: inside a cycle, the fast pointer gains one node per step on the slow pointer, so the gap closes and they must meet within one lap.
Finding the start: let a be the distance from head to the cycle start, b the distance from the start to the meeting point and L the cycle length. Fast has travelled twice as far as slow: 2(a + b) = a + b + kL for some whole number k, so a = kL - b. Starting from the meeting point, walking a steps is the same as walking kL - b steps, which lands exactly on the cycle start. A pointer from the head reaches the start after a steps too, so they meet there.
Complexity
O(n) time, O(1) extra space.
Code
python
class ListNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
def detect_cycle(head):
"""Floyd's algorithm. Return the node where the cycle starts, or None. O(1) space."""
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast: # they met inside the cycle
slow = head
while slow is not fast: # move both one step: they meet at the start
slow = slow.next
fast = fast.next
return slow
return None
def detect_cycle_set(head):
"""Brute force with a set of visited nodes. O(n) extra space."""
seen = set()
while head:
if head in seen:
return head
seen.add(head)
head = head.next
return None
def build(values, pos):
"""Build a list; the tail links to index pos (-1 for no cycle)."""
nodes = [ListNode(v) for v in values]
for a, b in zip(nodes, nodes[1:]):
a.next = b
if nodes and pos >= 0:
nodes[-1].next = nodes[pos]
return (nodes[0] if nodes else None), nodes
if __name__ == "__main__":
for f in (detect_cycle, detect_cycle_set):
head, nodes = build([3, 2, 0, -4], 1)
assert f(head) is nodes[1]
head, nodes = build([1, 2], 0)
assert f(head) is nodes[0]
head, nodes = build([1], -1)
assert f(head) is None
head, nodes = build([1], 0) # node pointing to itself
assert f(head) is nodes[0]
assert f(None) is None
for n in range(1, 12): # every list length and cycle start
for pos in range(-1, n):
head, nodes = build(list(range(n)), pos)
assert f(head) is (nodes[pos] if pos >= 0 else None)
print("all tests passed")
Save as a40_cycle.py and run python3 a40_cycle.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty list. One node with no cycle. One node pointing to itself. Cycle starting at the head. The test builds every length from 1 to 11 with every cycle start position. Compare nodes with is, not by value.
Pattern
Fast and slow pointers (Floyd's tortoise and hare). Also finds the middle of a list, checks a "happy number", and finds a duplicate number in an array of n + 1 values treated as a function graph.
python
class ListNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
def detect_cycle(head):
"""Floyd's algorithm. Return the node where the cycle starts, or None. O(1) space."""
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast: # they met inside the cycle
slow = head
while slow is not fast: # move both one step: they meet at the start
slow = slow.next
fast = fast.next
return slow
return None
def detect_cycle_set(head):
"""Brute force with a set of visited nodes. O(n) extra space."""
seen = set()
while head:
if head in seen:
return head
seen.add(head)
head = head.next
return None
def build(values, pos):
"""Build a list; the tail links to index pos (-1 for no cycle)."""
nodes = [ListNode(v) for v in values]
for a, b in zip(nodes, nodes[1:]):
a.next = b
if nodes and pos >= 0:
nodes[-1].next = nodes[pos]
return (nodes[0] if nodes else None), nodes
if __name__ == "__main__":
for f in (detect_cycle, detect_cycle_set):
head, nodes = build([3, 2, 0, -4], 1)
assert f(head) is nodes[1]
head, nodes = build([1, 2], 0)
assert f(head) is nodes[0]
head, nodes = build([1], -1)
assert f(head) is None
head, nodes = build([1], 0) # node pointing to itself
assert f(head) is nodes[0]
assert f(None) is None
for n in range(1, 12): # every list length and cycle start
for pos in range(-1, n):
head, nodes = build(list(range(n)), pos)
assert f(head) is (nodes[pos] if pos >= 0 else None)
print("all tests passed")
Floyd's algorithm with a visited-set reference; tests cover every list length 1 to 11 and every cycle position.
Complexity
Time: O(n). Space: O(1); the set version is O(n). The meeting-point argument a = kL - b explains the second phase.
By level
Fresher: Gives the set solution, then Floyd's detection with careful null checks. Should compare nodes by identity, not value.
Mid: Finds the cycle start and explains the distance equation clearly. Explains why the fast pointer cannot skip past the slow one without meeting it.
Senior: Applies the technique to function graphs such as finding duplicates, computes the cycle length, and compares with Brent's algorithm. Can explain how the method finds a duplicate in a list of n + 1 values.
Key points
Slow moves one step, fast moves two
Meeting means a cycle exists
Reset one pointer to head and move both one step
They meet at the cycle start because a = kL - b
O(1) extra space
Common mistakes
Checking fast.next.next without checking fast.next