← Interview prep

Algorithms interview questions

Problem-solving patterns, complexity, and coding-round staples.

100 questions · Page 5 of 5

Want the full pack? Interview packs · Mock interview · Mentora

Page 5 of 5

Questions 81–100 of 100 · 0 of 20 on this page marked learned

81.algorithms-0081Mediummid

0/1 knapsack: choose items with given weights and values to maximise total value without exceeding a weight capacity, using each item at most once.

Let best[c] be the best value with capacity c using the items seen so far. For each item, update capacities from high to low: best[c] = max(best[c], best[c - w] + v). The downward order keeps each item from being used twice. Time O(n * cap), space O(cap); a 2D table is needed to recover which items were taken.

Full answer

Problem

Given n items with weights w[i] and values v[i] and a capacity W, return the maximum total value of a subset whose total weight is at most W.

Example: weights [1, 3, 4, 5], values [1, 4, 5, 7], W = 7 returns 9 (items of weight 3 and 4).

Constraints: n <= 100, W <= 10^4, weights and values positive integers.

Brute force

Try all 2^n subsets and keep the best feasible one: O(2^n * n).

Optimal approach

2D form: dp[i][c] = best value using the first i items with capacity c. Then dp[i][c] = dp[i-1][c] (skip) or dp[i-1][c - w] + v (take, if w <= c).

1D form: one array best[0..W]. For each item, loop c from W down to w and set best[c] = max(best[c], best[c - w] + v).

To recover the items, keep the 2D table and walk back from dp[n][W]: if dp[i][c] != dp[i-1][c], item i was taken, so subtract its weight.

Why it works

For the first i items and capacity c, an optimal choice either excludes item i (leaving the problem for i - 1 items and capacity c) or includes it (leaving i - 1 items and capacity c - w). Both are smaller subproblems, so the recurrence is complete. In the 1D form, iterating c downward means best[c - w] still holds the value from before item i was considered, which enforces "at most once". Iterating upward would turn it into the unbounded knapsack.

Complexity

O(n * W) time; O(W) space for the value only, O(n * W) to recover items. This is pseudo-polynomial; the decision version of knapsack is NP-complete, so no algorithm polynomial in the number of input bits is known.

Code

python
import random
from itertools import product


def knapsack(weights, values, cap):
    """0/1 knapsack: each item used at most once. 1D table iterated from high capacity down.
    O(n * cap) time, O(cap) space (pseudo-polynomial)."""
    best = [0] * (cap + 1)
    for w, v in zip(weights, values):
        for c in range(cap, w - 1, -1):  # downward so item i is not reused in the same pass
            best[c] = max(best[c], best[c - w] + v)
    return best[cap]


def knapsack_with_items(weights, values, cap):
    """2D table so the chosen items can be recovered."""
    n = len(weights)
    dp = [[0] * (cap + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        w, v = weights[i - 1], values[i - 1]
        for c in range(cap + 1):
            dp[i][c] = dp[i - 1][c]
            if w <= c:
                dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v)
    chosen, c = [], cap
    for i in range(n, 0, -1):
        if dp[i][c] != dp[i - 1][c]:
            chosen.append(i - 1)
            c -= weights[i - 1]
    return dp[n][cap], chosen[::-1]


def brute(weights, values, cap):
    best = 0
    for pick in product((0, 1), repeat=len(weights)):
        if sum(w for w, p in zip(weights, pick) if p) <= cap:
            best = max(best, sum(v for v, p in zip(values, pick) if p))
    return best


if __name__ == "__main__":
    assert knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7) == 9          # items of weight 3 and 4
    total, items = knapsack_with_items([1, 3, 4, 5], [1, 4, 5, 7], 7)
    assert total == 9 and sum([1, 3, 4, 5][i] for i in items) <= 7
    assert knapsack([], [], 10) == 0 and knapsack([5], [10], 4) == 0
    rng = random.Random(81)
    for _ in range(500):
        n = rng.randint(0, 9)
        ws = [rng.randint(1, 10) for _ in range(n)]
        vs = [rng.randint(0, 20) for _ in range(n)]
        cap = rng.randint(0, 30)
        t, its = knapsack_with_items(ws, vs, cap)
        assert knapsack(ws, vs, cap) == t == brute(ws, vs, cap) == sum(vs[i] for i in its)
    print("all tests passed")

Save as b81_knapsack.py and run python3 b81_knapsack.py. It prints all tests passed (Python 3.13.5).

Edge cases

No items or capacity 0 (value 0). Items heavier than the capacity (never taken). Zero-value items. Very large W with small n: switch to a DP over value (min weight for each value) or meet-in-the-middle over subsets.

Pattern

0/1 knapsack: a decision per item with a resource budget, iterating the budget downward in the 1D form. Same shape: partition equal subset sum, target sum with plus and minus signs, last stone weight II, and budgeted feature selection.

python
import random
from itertools import product


def knapsack(weights, values, cap):
    """0/1 knapsack: each item used at most once. 1D table iterated from high capacity down.
    O(n * cap) time, O(cap) space (pseudo-polynomial)."""
    best = [0] * (cap + 1)
    for w, v in zip(weights, values):
        for c in range(cap, w - 1, -1):  # downward so item i is not reused in the same pass
            best[c] = max(best[c], best[c - w] + v)
    return best[cap]


def knapsack_with_items(weights, values, cap):
    """2D table so the chosen items can be recovered."""
    n = len(weights)
    dp = [[0] * (cap + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        w, v = weights[i - 1], values[i - 1]
        for c in range(cap + 1):
            dp[i][c] = dp[i - 1][c]
            if w <= c:
                dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v)
    chosen, c = [], cap
    for i in range(n, 0, -1):
        if dp[i][c] != dp[i - 1][c]:
            chosen.append(i - 1)
            c -= weights[i - 1]
    return dp[n][cap], chosen[::-1]


def brute(weights, values, cap):
    best = 0
    for pick in product((0, 1), repeat=len(weights)):
        if sum(w for w, p in zip(weights, pick) if p) <= cap:
            best = max(best, sum(v for v, p in zip(values, pick) if p))
    return best


if __name__ == "__main__":
    assert knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7) == 9          # items of weight 3 and 4
    total, items = knapsack_with_items([1, 3, 4, 5], [1, 4, 5, 7], 7)
    assert total == 9 and sum([1, 3, 4, 5][i] for i in items) <= 7
    assert knapsack([], [], 10) == 0 and knapsack([5], [10], 4) == 0
    rng = random.Random(81)
    for _ in range(500):
        n = rng.randint(0, 9)
        ws = [rng.randint(1, 10) for _ in range(n)]
        vs = [rng.randint(0, 20) for _ in range(n)]
        cap = rng.randint(0, 30)
        t, its = knapsack_with_items(ws, vs, cap)
        assert knapsack(ws, vs, cap) == t == brute(ws, vs, cap) == sum(vs[i] for i in its)
    print("all tests passed")

1D downward table, 2D table with item recovery, and an exhaustive subset check on random instances.

Complexity

Time: O(n * W). Space: O(W) value only; O(n * W) with item recovery. Pseudo-polynomial; for huge W and small n, use DP over value or meet-in-the-middle.

By level

Fresher: Writes the 2D table with take or skip and fills it on a small example. Explains why greedy by ratio does not work for 0/1 items.

Mid: Compresses to 1D with the downward loop and explains why the direction matters. Recovers chosen items from the 2D table.

Senior: Discusses pseudo-polynomial time and NP-completeness, DP over value, meet-in-the-middle, and approximation schemes. Applies multi-constraint knapsack thinking to resource allocation.

Key points

  • Take or skip each item once
  • 1D loop runs capacity downward
  • Upward loop gives unbounded knapsack
  • Recover items from the 2D table
  • Pseudo-polynomial O(n * W)

Common mistakes

  • Iterating capacity upward in the 1D version
  • Sorting by value-to-weight ratio greedily (that is only correct for fractional knapsack)
  • Losing the item list after compressing to 1D
  • Calling O(n * W) polynomial without qualification

Follow-ups

  • How do you solve it if W is 10^9 but n is 40?
  • How does fractional knapsack differ?
  • How would you handle a second constraint such as volume?

Tips

  • State the take-or-skip recurrence before coding
  • Explain the downward loop
  • Mention pseudo-polynomial time

Evaluation rubric

  • Correct recurrence
  • Correct loop direction
  • Item recovery
  • Correct complexity discussion
82.algorithms-0082Hardsenior

Edit distance: compute the minimum number of single-character insertions, deletions and replacements needed to turn one string into another.

Let d[i][j] be the distance between the first i characters of a and the first j of b. If the last characters match, d[i][j] = d[i-1][j-1]; otherwise it is 1 plus the minimum of delete (d[i-1][j]), insert (d[i][j-1]) and replace (d[i-1][j-1]). Base cases are i and j. Time O(m * n); two rolling rows give O(min(m, n)) space.

Full answer

Problem

Given strings a and b, return the minimum number of operations to convert a into b, where an operation inserts, deletes or replaces one character.

Example: horse to ros takes 3 (replace h with r, delete r, delete e). intention to execution takes 5.

Constraints: 0 <= len(a), len(b) <= 500, lowercase letters.

Brute force

Recursively compare from the front: if the first characters match, move both; otherwise try all three operations and take the best. Without memoization this is O(3^(m+n)). With memoization it becomes the DP below (the test reference uses memoized recursion for clarity).

Optimal approach

Table d of size (m + 1) x (n + 1):

  • d[i][0] = i (delete everything), d[0][j] = j (insert everything).
  • If a[i-1] == b[j-1]: d[i][j] = d[i-1][j-1].
  • Else: d[i][j] = 1 + min(d[i-1][j], d[i][j-1], d[i-1][j-1]).

Row i only depends on row i - 1, so keep two rows, and put the shorter string along the row to use O(min(m, n)) space.

Why it works

Look at the last characters of the two prefixes. In an optimal edit script, either the last character of a is deleted, a character is inserted to produce the last character of b, or the last characters are aligned (free if equal, one replacement if not). Each case leaves a smaller pair of prefixes, and taking the minimum over the cases covers every script. The base cases are the cost of turning a prefix into the empty string and back.

Complexity

O(m * n) time; O(min(m, n)) space with rolling rows, or O(m * n) if the actual edit script must be reconstructed (or use Hirschberg's divide and conquer to reconstruct in linear space).

Code

python
import random
from functools import lru_cache


def edit_distance(a, b):
    """Levenshtein distance (insert, delete, replace each cost 1).
    Two rolling rows: O(len(a) * len(b)) time, O(min(len)) space."""
    if len(a) < len(b):
        a, b = b, a                      # keep the row over the shorter string
    prev = list(range(len(b) + 1))       # distance from "" to b[:j]
    for i in range(1, len(a) + 1):
        cur = [i] + [0] * len(b)
        for j in range(1, len(b) + 1):
            if a[i - 1] == b[j - 1]:
                cur[j] = prev[j - 1]
            else:
                cur[j] = 1 + min(prev[j],       # delete a[i-1]
                                 cur[j - 1],    # insert b[j-1]
                                 prev[j - 1])   # replace
        prev = cur
    return prev[-1]


def brute(a, b):
    @lru_cache(maxsize=None)
    def go(i, j):                        # plain recursion over suffixes, memoised only for speed
        if i == len(a):
            return len(b) - j
        if j == len(b):
            return len(a) - i
        if a[i] == b[j]:
            return go(i + 1, j + 1)
        return 1 + min(go(i + 1, j), go(i, j + 1), go(i + 1, j + 1))
    return go(0, 0)


if __name__ == "__main__":
    assert edit_distance("horse", "ros") == 3
    assert edit_distance("intention", "execution") == 5
    assert edit_distance("", "abc") == 3 and edit_distance("abc", "") == 3
    assert edit_distance("same", "same") == 0
    rng = random.Random(82)
    for _ in range(1000):
        a = "".join(rng.choice("abc") for _ in range(rng.randint(0, 8)))
        b = "".join(rng.choice("abc") for _ in range(rng.randint(0, 8)))
        d = edit_distance(a, b)
        assert d == brute(a, b) == edit_distance(b, a)
        assert abs(len(a) - len(b)) <= d <= max(len(a), len(b))
    print("all tests passed")

Save as b82_edit_distance.py and run python3 b82_edit_distance.py. It prints all tests passed (Python 3.13.5).

Edge cases

One or both strings empty (the other's length). Identical strings (0). Completely different strings of equal length (the length, all replacements). The distance is symmetric and at least the length difference; the tests check both properties.

Pattern

Two-sequence DP on prefixes, the same family as longest common subsequence. Variants: only insert and delete (equals m + n - 2 * LCS), weighted operation costs, one edit away (O(n) check), and banded DP when only distances up to k matter, which gives O(n * k).

python
import random
from functools import lru_cache


def edit_distance(a, b):
    """Levenshtein distance (insert, delete, replace each cost 1).
    Two rolling rows: O(len(a) * len(b)) time, O(min(len)) space."""
    if len(a) < len(b):
        a, b = b, a                      # keep the row over the shorter string
    prev = list(range(len(b) + 1))       # distance from "" to b[:j]
    for i in range(1, len(a) + 1):
        cur = [i] + [0] * len(b)
        for j in range(1, len(b) + 1):
            if a[i - 1] == b[j - 1]:
                cur[j] = prev[j - 1]
            else:
                cur[j] = 1 + min(prev[j],       # delete a[i-1]
                                 cur[j - 1],    # insert b[j-1]
                                 prev[j - 1])   # replace
        prev = cur
    return prev[-1]


def brute(a, b):
    @lru_cache(maxsize=None)
    def go(i, j):                        # plain recursion over suffixes, memoised only for speed
        if i == len(a):
            return len(b) - j
        if j == len(b):
            return len(a) - i
        if a[i] == b[j]:
            return go(i + 1, j + 1)
        return 1 + min(go(i + 1, j), go(i, j + 1), go(i + 1, j + 1))
    return go(0, 0)


if __name__ == "__main__":
    assert edit_distance("horse", "ros") == 3
    assert edit_distance("intention", "execution") == 5
    assert edit_distance("", "abc") == 3 and edit_distance("abc", "") == 3
    assert edit_distance("same", "same") == 0
    rng = random.Random(82)
    for _ in range(1000):
        a = "".join(rng.choice("abc") for _ in range(rng.randint(0, 8)))
        b = "".join(rng.choice("abc") for _ in range(rng.randint(0, 8)))
        d = edit_distance(a, b)
        assert d == brute(a, b) == edit_distance(b, a)
        assert abs(len(a) - len(b)) <= d <= max(len(a), len(b))
    print("all tests passed")

Two-row Levenshtein with the shorter string on the row, checked against memoized recursion and symmetry and bound properties on random strings.

Complexity

Time: O(m * n). Space: O(min(m, n)). Banded DP limits work to O(n * k) when only distances up to k matter.

By level

Fresher: Explains the three operations on the last characters and fills a small table by hand. Writes the full 2D version.

Mid: Compresses to two rows and reconstructs an edit script from the full table. Solves the one-edit-away variant in linear time.

Senior: Discusses banded DP for bounded distances, BK-trees or tries for fuzzy dictionary search, and Hirschberg's method for linear-space reconstruction. Relates the problem to diff tools and sequence alignment with weighted costs.

Key points

  • State over prefixes of both strings
  • Match costs 0, else 1 + min of three moves
  • Base cases are the prefix lengths
  • Two rows give linear space
  • Related to LCS

Common mistakes

  • Mixing up which neighbour is insert and which is delete
  • Wrong base row and column
  • Overwriting the diagonal value too early in a rolling row
  • Forgetting the equal-character shortcut

Follow-ups

  • How would you reconstruct the sequence of edits?
  • How do you check "one edit away" in O(n)?
  • How would you search a dictionary for words within distance 2 of a query?

Tips

  • Explain the three cases with the last characters
  • Fill a small table by hand
  • Mention the two-row optimization

Evaluation rubric

  • Correct recurrence and bases
  • Correct complexity
  • Space optimization
  • Handles empty strings
83.algorithms-0083Mediummid

Word break: decide whether a string can be split into a sequence of dictionary words, and list every possible sentence when asked.

Let ok[i] mean the prefix of length i can be split. Then ok[0] is True and ok[i] is True if some ok[j] is True and s[j:i] is a dictionary word. Limiting j to the last L positions, where L is the longest word, gives O(n * L) substring checks. Listing all sentences needs memoized recursion over start positions, and the output itself can be exponential.

Full answer

Problem

Given a string s and a list of words, return True if s can be segmented into one or more dictionary words (words may repeat). Follow-up: return all such segmentations as space-separated sentences.

Example: "leetcode" with ["leet", "code"] is True; "catsandog" with ["cats", "dog", "sand", "and", "cat"] is False; "catsanddog" has two sentences: "cat sand dog" and "cats and dog".

Constraints: 1 <= len(s) <= 300, up to 1,000 words of length up to 20.

Brute force

Try every word as a prefix and recurse on the rest. Without memoization a string like "aaaa...ab" with words "a", "aa", "aaa" causes exponential work, because the same suffix is retried along many paths.

Optimal approach

  1. Put words in a set; let L be the longest word length.
  2. ok = [True] + [False] * n.
  3. For i from 1 to n, for j from max(0, i - L) to i - 1: if ok[j] and s[j:i] is in the set, set ok[i] = True and stop scanning j.
  4. Return ok[n].

All sentences: memoize go(i) = list of sentences for s[i:], trying each end j where s[i:j] is a word.

Why it works

A valid split of the first i characters has a last word s[j:i], and the part before it must itself be a valid split, which is ok[j]. Checking all j covers every possible last word; words longer than L cannot match, so the restricted range loses nothing. Memoizing by start index in the listing version means each suffix's sentences are built once.

Complexity

Decision: O(n * L) set lookups, each hashing a substring of length up to L, so O(n * L^2) character work in the worst case; O(n) space. A trie walk from each start position avoids rebuilding substrings. Listing: output-sensitive and exponential in the worst case.

Code

python
import random
from functools import lru_cache


def word_break(s, words):
    """Can s be split into dictionary words? dp[i] = some j < i with dp[j] and s[j:i] in words.
    Only look back as far as the longest word: O(n * L) substring checks."""
    wordset = set(words)
    if not wordset:
        return s == ""
    longest = max(map(len, wordset))
    ok = [True] + [False] * len(s)
    for i in range(1, len(s) + 1):
        for j in range(max(0, i - longest), i):
            if ok[j] and s[j:i] in wordset:
                ok[i] = True
                break
    return ok[-1]


def word_break_all(s, words):
    """Every sentence (can be exponential in count); memoised by start index."""
    wordset = set(words)

    @lru_cache(maxsize=None)
    def go(i):
        if i == len(s):
            return [""]
        out = []
        for j in range(i + 1, len(s) + 1):
            if s[i:j] in wordset:
                out += [s[i:j] + (" " + rest if rest else "") for rest in go(j)]
        return out
    return sorted(go(0))


def brute(s, words):
    """Try every prefix recursively, no memo: exponential."""
    if s == "":
        return True
    return any(s.startswith(w) and brute(s[len(w):], words) for w in words if w)


if __name__ == "__main__":
    assert word_break("leetcode", ["leet", "code"])
    assert word_break("applepenapple", ["apple", "pen"])
    assert not word_break("catsandog", ["cats", "dog", "sand", "and", "cat"])
    assert word_break("", ["a"]) and not word_break("a", [])
    assert word_break_all("catsanddog", ["cat", "cats", "and", "sand", "dog"]) == ["cat sand dog", "cats and dog"]
    rng = random.Random(83)
    for _ in range(1000):
        words = list({"".join(rng.choice("ab") for _ in range(rng.randint(1, 3))) for _ in range(rng.randint(0, 4))})
        s = "".join(rng.choice("ab") for _ in range(rng.randint(0, 10)))
        assert word_break(s, words) == brute(s, words) == bool(word_break_all(s, words))
    print("all tests passed")

Save as b83_word_break.py and run python3 b83_word_break.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty string (True: zero words). Empty dictionary. A word that is a prefix of another (cat, cats). Repeated words. Very long strings with short words (L keeps the inner loop short).

Pattern

Prefix segmentation DP: "can prefix i be completed from some earlier valid point". Related: palindrome partitioning (minimum cuts), decode ways, concatenated words, and sentence segmentation for languages written without spaces.

python
import random
from functools import lru_cache


def word_break(s, words):
    """Can s be split into dictionary words? dp[i] = some j < i with dp[j] and s[j:i] in words.
    Only look back as far as the longest word: O(n * L) substring checks."""
    wordset = set(words)
    if not wordset:
        return s == ""
    longest = max(map(len, wordset))
    ok = [True] + [False] * len(s)
    for i in range(1, len(s) + 1):
        for j in range(max(0, i - longest), i):
            if ok[j] and s[j:i] in wordset:
                ok[i] = True
                break
    return ok[-1]


def word_break_all(s, words):
    """Every sentence (can be exponential in count); memoised by start index."""
    wordset = set(words)

    @lru_cache(maxsize=None)
    def go(i):
        if i == len(s):
            return [""]
        out = []
        for j in range(i + 1, len(s) + 1):
            if s[i:j] in wordset:
                out += [s[i:j] + (" " + rest if rest else "") for rest in go(j)]
        return out
    return sorted(go(0))


def brute(s, words):
    """Try every prefix recursively, no memo: exponential."""
    if s == "":
        return True
    return any(s.startswith(w) and brute(s[len(w):], words) for w in words if w)


if __name__ == "__main__":
    assert word_break("leetcode", ["leet", "code"])
    assert word_break("applepenapple", ["apple", "pen"])
    assert not word_break("catsandog", ["cats", "dog", "sand", "and", "cat"])
    assert word_break("", ["a"]) and not word_break("a", [])
    assert word_break_all("catsanddog", ["cat", "cats", "and", "sand", "dog"]) == ["cat sand dog", "cats and dog"]
    rng = random.Random(83)
    for _ in range(1000):
        words = list({"".join(rng.choice("ab") for _ in range(rng.randint(1, 3))) for _ in range(rng.randint(0, 4))})
        s = "".join(rng.choice("ab") for _ in range(rng.randint(0, 10)))
        assert word_break(s, words) == brute(s, words) == bool(word_break_all(s, words))
    print("all tests passed")

Boolean prefix DP bounded by the longest word and a memoized sentence lister, cross-checked against plain recursion on random strings and dictionaries.

Complexity

Time: O(n * L) lookups. Space: O(n). Each lookup hashes a substring of up to L characters; a trie avoids building substrings. Listing all sentences is output-sensitive.

By level

Fresher: Writes the boolean prefix table with a set of words and traces it on a short example. Explains why greedy longest match fails.

Mid: Bounds the inner loop by the longest word, writes the memoized sentence lister, and discusses output size. Uses a trie to avoid substring building.

Senior: Discusses segmentation for search queries and languages without spaces, ranking splits with word frequencies, and memory for large dictionaries. Evaluates trie versus hashing for lookup speed.

Key points

  • ok[i] true if some ok[j] and s[j:i] is a word
  • Limit j by the longest word
  • Use a set (or trie) for lookups
  • Memoize by start index for the listing version
  • Listing output can be exponential

Common mistakes

  • Greedy longest-match splitting
  • Recursion without memoization
  • Checking all j without the L bound on long strings
  • Forgetting that words may repeat

Follow-ups

  • How would you find the split with the fewest words?
  • How would a trie speed this up?
  • How would you handle a dictionary of millions of words?

Tips

  • Show why greedy matching fails
  • Explain the L bound
  • Mention exponential output for the listing version

Evaluation rubric

  • Correct DP
  • Uses a set
  • Correct complexity
  • Handles the listing follow-up
84.algorithms-0084Mediumfresher

Unique paths in a grid: count the ways to go from the top-left to the bottom-right cell moving only right or down, first on an open grid and then with blocked cells.

The number of ways to reach a cell is the number of ways to reach the cell above plus the cell to the left. One rolling row gives O(m * n) time and O(n) space. Without obstacles the answer is the binomial coefficient C(m + n - 2, m - 1). Blocked cells contribute 0 ways.

Full answer

Problem

A robot starts at the top-left of an m x n grid and moves only right or down. Return the number of distinct paths to the bottom-right cell. Then solve it when some cells (marked 1) are blocked.

Example: a 3 x 7 grid has 28 paths; a 3 x 2 grid has 3. The grid [[0,0,0],[0,1,0],[0,0,0]] has 2 paths.

Constraints: 1 <= m, n <= 100; answers fit in a 64-bit integer for the classic limits.

Brute force

Recursively try moving right and down from each cell and count arrivals: O(2^(m+n)), because cells are revisited along many paths.

Optimal approach

row = [1] * n for the first row. For each later row, for j from 1 to n - 1: row[j] += row[j - 1] (the old row[j] is the value from above, row[j - 1] is the value from the left).

With obstacles: start row = [1, 0, ..., 0]; for every row, set row[j] = 0 at blocked cells, else add row[j - 1] when j > 0.

Closed form (no obstacles): choose which m - 1 of the m + n - 2 moves are downs: C(m + n - 2, m - 1).

Why it works

Every path into a cell arrives from above or from the left, and those two groups do not overlap, so their counts add. Filling row by row, left to right, guarantees both neighbours are ready. A blocked cell has no paths through it, so it contributes 0 to its neighbours. In the closed form, a path is just a sequence of m - 1 downs and n - 1 rights in some order.

Complexity

O(m * n) time and O(n) space for the DP; O(min(m, n)) arithmetic steps for the binomial.

Code

python
import random
from math import comb


def unique_paths(m, n):
    """Right/down moves on an m x n grid. One rolling row: O(m * n) time, O(n) space."""
    row = [1] * n
    for _ in range(1, m):
        for j in range(1, n):
            row[j] += row[j - 1]         # from above (old row[j]) + from the left
    return row[-1]


def unique_paths_math(m, n):
    """Choose which of the m+n-2 moves are downs: C(m+n-2, m-1)."""
    return comb(m + n - 2, m - 1)


def unique_paths_obstacles(grid):
    """1 marks a blocked cell."""
    n = len(grid[0])
    row = [0] * n
    row[0] = 1
    for r in grid:
        for j in range(n):
            if r[j]:
                row[j] = 0
            elif j:
                row[j] += row[j - 1]
    return row[-1]


def brute(grid, r=0, c=0):
    m, n = len(grid), len(grid[0])
    if r >= m or c >= n or grid[r][c]:
        return 0
    if (r, c) == (m - 1, n - 1):
        return 1
    return brute(grid, r + 1, c) + brute(grid, r, c + 1)


if __name__ == "__main__":
    assert unique_paths(3, 7) == 28 and unique_paths(3, 2) == 3 and unique_paths(1, 1) == 1
    assert all(unique_paths(m, n) == unique_paths_math(m, n) for m in range(1, 12) for n in range(1, 12))
    assert unique_paths_obstacles([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) == 2
    assert unique_paths_obstacles([[1]]) == 0 and unique_paths_obstacles([[0, 1], [1, 0]]) == 0
    rng = random.Random(84)
    for _ in range(500):
        m, n = rng.randint(1, 6), rng.randint(1, 6)
        g = [[int(rng.random() < 0.2) for _ in range(n)] for _ in range(m)]
        assert unique_paths_obstacles(g) == brute(g)
    print("all tests passed")

Save as b84_unique_paths.py and run python3 b84_unique_paths.py. It prints all tests passed (Python 3.13.5).

Edge cases

1 x 1 grid (1 path). A single row or column (1 path). Blocked start or end (0). A wall that cuts the grid (0). Large grids where counts overflow 64 bits (Python is exact; elsewhere use modular arithmetic or big integers).

Pattern

Grid DP where each cell combines its predecessors. Related: minimum path sum (min instead of sum), dungeon game (fill backwards from the end), cherry pickup, and counting lattice paths with combinatorics.

python
import random
from math import comb


def unique_paths(m, n):
    """Right/down moves on an m x n grid. One rolling row: O(m * n) time, O(n) space."""
    row = [1] * n
    for _ in range(1, m):
        for j in range(1, n):
            row[j] += row[j - 1]         # from above (old row[j]) + from the left
    return row[-1]


def unique_paths_math(m, n):
    """Choose which of the m+n-2 moves are downs: C(m+n-2, m-1)."""
    return comb(m + n - 2, m - 1)


def unique_paths_obstacles(grid):
    """1 marks a blocked cell."""
    n = len(grid[0])
    row = [0] * n
    row[0] = 1
    for r in grid:
        for j in range(n):
            if r[j]:
                row[j] = 0
            elif j:
                row[j] += row[j - 1]
    return row[-1]


def brute(grid, r=0, c=0):
    m, n = len(grid), len(grid[0])
    if r >= m or c >= n or grid[r][c]:
        return 0
    if (r, c) == (m - 1, n - 1):
        return 1
    return brute(grid, r + 1, c) + brute(grid, r, c + 1)


if __name__ == "__main__":
    assert unique_paths(3, 7) == 28 and unique_paths(3, 2) == 3 and unique_paths(1, 1) == 1
    assert all(unique_paths(m, n) == unique_paths_math(m, n) for m in range(1, 12) for n in range(1, 12))
    assert unique_paths_obstacles([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) == 2
    assert unique_paths_obstacles([[1]]) == 0 and unique_paths_obstacles([[0, 1], [1, 0]]) == 0
    rng = random.Random(84)
    for _ in range(500):
        m, n = rng.randint(1, 6), rng.randint(1, 6)
        g = [[int(rng.random() < 0.2) for _ in range(n)] for _ in range(m)]
        assert unique_paths_obstacles(g) == brute(g)
    print("all tests passed")

Rolling-row counts, the binomial closed form, and the obstacle version cross-checked against plain recursion on random small grids.

Complexity

Time: O(m * n). Space: O(n). The binomial needs O(min(m, n)) multiplications.

By level

Fresher: Fills the table by adding the cell above and the cell to the left, and explains why. Handles blocked cells by setting them to 0.

Mid: Reduces space to one row, derives the binomial formula, and explains why it fails with obstacles. Adapts the DP to minimum path sum.

Senior: Computes large answers with modular binomials and factorial tables, and discusses inclusion-exclusion for a few obstacles on huge grids. Relates grid DP fill order to dependency direction in more complex problems.

Key points

  • ways(cell) = ways(up) + ways(left)
  • One row is enough
  • Blocked cells contribute 0
  • Closed form C(m+n-2, m-1)
  • Fill order guarantees dependencies are ready

Common mistakes

  • Initializing the first column wrong when obstacles appear
  • Forgetting that a blocked start makes the answer 0
  • Using the closed form when obstacles exist
  • Integer overflow in fixed-width languages

Follow-ups

  • How do you find the minimum path sum instead?
  • What if the robot may also move diagonally?
  • How would you compute the answer modulo 10^9 + 7 for a 10^5 x 10^5 grid?

Tips

  • Show the 2 x 2 or 3 x 3 table by hand
  • Mention the combinatorial formula
  • Handle obstacles in the first row and column

Evaluation rubric

  • Correct recurrence
  • Space optimization
  • Correct obstacle handling
  • Knows the closed form
85.algorithms-0085Mediummid

Partition equal subset sum: decide whether an array of positive integers can be split into two subsets with equal sums.

A split exists exactly when some subset sums to half the total, so return False for an odd total and otherwise solve subset sum for total/2. A boolean table reach[s] updated from high to low for each number takes O(n * total) time and O(total) space. In Python a big integer used as a bitset (bits |= bits << x) does the same work very quickly.

Full answer

Problem

Given an array of positive integers, return True if it can be partitioned into two subsets with equal sums.

Example: [1, 5, 11, 5] is True (11 and 1 + 5 + 5); [1, 2, 3, 5] is False (total 11 is odd).

Constraints: 1 <= n <= 200, values from 1 to 100, so the total is at most 20,000.

Brute force

Try all 2^n subsets and check whether one sums to half the total: O(2^n * n).

Optimal approach

  1. If the total is odd, return False. Let target = total // 2.
  2. reach = [True] + [False] * target (sum 0 is always reachable with the empty subset).
  3. For each x, for s from target down to x: reach[s] |= reach[s - x]. Stop early once reach[target] is True.
  4. Return reach[target].

Bitset version: bits = 1; for each x, bits |= bits << x; check bit target.

Why it works

The two parts have equal sums exactly when one part sums to total/2, because the other part then holds the rest. After processing the first k numbers, reach[s] says whether some subset of them sums to s. Each new number either joins a subset (moving s - x to s) or not, and the downward loop makes sure each number is added at most once. The bitset shift performs that "add x to every reachable sum" step for all sums at once.

Complexity

O(n * target) time, O(target) space. The bitset version has the same bound in bit operations but processes many sums per machine word.

Code

python
import random
from itertools import product


def can_partition(nums):
    """Split into two subsets of equal sum? Equivalent to: is there a subset summing to total/2.
    Boolean 0/1 knapsack, O(n * total) time, O(total) space."""
    total = sum(nums)
    if total % 2:
        return False
    target = total // 2
    reach = [True] + [False] * target
    for x in nums:
        for s in range(target, x - 1, -1):     # downward: each number used once
            if reach[s - x]:
                reach[s] = True
        if reach[target]:
            return True
    return reach[target]


def can_partition_bitset(nums):
    """Same idea with a Python int as a bitset: bit s set means sum s is reachable."""
    total = sum(nums)
    if total % 2:
        return False
    bits = 1
    for x in nums:
        bits |= bits << x
    return bool(bits >> (total // 2) & 1)


def brute(nums):
    total = sum(nums)
    return any(2 * sum(x for x, p in zip(nums, pick) if p) == total for pick in product((0, 1), repeat=len(nums)))


if __name__ == "__main__":
    assert can_partition([1, 5, 11, 5])                 # 11 = 1 + 5 + 5
    assert not can_partition([1, 2, 3, 5])
    assert not can_partition([1]) and can_partition([]) and can_partition([2, 2])
    rng = random.Random(85)
    for _ in range(1000):
        a = [rng.randint(1, 15) for _ in range(rng.randint(0, 10))]
        assert can_partition(a) == can_partition_bitset(a) == brute(a)
    print("all tests passed")

Save as b85_partition_equal.py and run python3 b85_partition_equal.py. It prints all tests passed (Python 3.13.5).

Edge cases

Odd total (False immediately). Single element (False). Empty array (True: both parts are empty, a convention to confirm). One element larger than half the total (False). Many duplicates.

Pattern

Subset sum as 0/1 knapsack with boolean values. Related: target sum with plus and minus signs (reduce to a subset sum of (total + target) / 2), last stone weight II (closest reachable sum to total/2), and partition into k equal subsets (backtracking with pruning or bitmask DP).

python
import random
from itertools import product


def can_partition(nums):
    """Split into two subsets of equal sum? Equivalent to: is there a subset summing to total/2.
    Boolean 0/1 knapsack, O(n * total) time, O(total) space."""
    total = sum(nums)
    if total % 2:
        return False
    target = total // 2
    reach = [True] + [False] * target
    for x in nums:
        for s in range(target, x - 1, -1):     # downward: each number used once
            if reach[s - x]:
                reach[s] = True
        if reach[target]:
            return True
    return reach[target]


def can_partition_bitset(nums):
    """Same idea with a Python int as a bitset: bit s set means sum s is reachable."""
    total = sum(nums)
    if total % 2:
        return False
    bits = 1
    for x in nums:
        bits |= bits << x
    return bool(bits >> (total // 2) & 1)


def brute(nums):
    total = sum(nums)
    return any(2 * sum(x for x, p in zip(nums, pick) if p) == total for pick in product((0, 1), repeat=len(nums)))


if __name__ == "__main__":
    assert can_partition([1, 5, 11, 5])                 # 11 = 1 + 5 + 5
    assert not can_partition([1, 2, 3, 5])
    assert not can_partition([1]) and can_partition([]) and can_partition([2, 2])
    rng = random.Random(85)
    for _ in range(1000):
        a = [rng.randint(1, 15) for _ in range(rng.randint(0, 10))]
        assert can_partition(a) == can_partition_bitset(a) == brute(a)
    print("all tests passed")

Boolean downward table with early exit and a big-integer bitset, cross-checked against all subsets on random arrays.

Complexity

Time: O(n * total). Space: O(total). Pseudo-polynomial in the total; the bitset version is much faster in practice.

By level

Fresher: Explains why the question reduces to finding a subset with half the total and writes the boolean table. Handles the odd total case.

Mid: Uses the downward 1D loop, stops early, and presents the bitset version. Reduces target sum to the same problem.

Senior: Discusses meet-in-the-middle for large values with small n, k-way partitioning with bitmask DP, and pseudo-polynomial limits. Applies the idea to load balancing across two machines.

Key points

  • Reduce to subset sum of total / 2
  • Odd total means False
  • Boolean knapsack with a downward loop
  • Bitset shift handles all sums at once
  • Pseudo-polynomial

Common mistakes

  • Forgetting the odd-total check
  • Looping upward and reusing a number
  • Sorting and greedily filling one side
  • Using a set of sums that grows without bound on large inputs

Follow-ups

  • How would you split into k equal subsets?
  • How does target sum with signs reduce to this?
  • What if values are up to 10^9 but n is 30?

Tips

  • State the reduction to total/2 first
  • Explain the downward loop
  • Mention the bitset trick

Evaluation rubric

  • Correct reduction
  • Correct DP
  • Handles odd totals
  • Correct complexity
86.algorithms-0086Mediummid

Decode ways: count how many ways a digit string can be decoded when 'A' maps to 1 through 'Z' to 26, handling zeros correctly.

Let ways(i) be the number of decodings of the first i digits. The last digit alone adds ways(i-1) if it is not '0', and the last two digits add ways(i-2) if they form a number from 10 to 26. Two running variables give O(n) time and O(1) space. Zeros are the trap: '0' can only appear as part of 10 or 20.

Full answer

Problem

A message of letters was encoded as digits with A = 1, ..., Z = 26. Given the digit string, return the number of ways to decode it. Return 0 if no decoding exists.

Example: "12" gives 2 (AB, L); "226" gives 3 (BBF, BZ, VF); "06" gives 0; "10" gives 1.

Constraints: 1 <= len(s) <= 100; digits only; the answer fits in a 32-bit integer.

Brute force

Recursively take one digit (if not 0) or two digits (if between 10 and 26) and recurse on the rest. Without memoization this is exponential, close to Fibonacci growth on strings of 1s and 2s.

Optimal approach

  1. If s starts with '0', return 0.
  2. prev2 = 1 (empty prefix), prev1 = 1 (first digit).
  3. For i from 2 to n: cur = 0; if s[i-1] != '0', add prev1; if 10 <= int(s[i-2:i]) <= 26, add prev2. Shift: prev2, prev1 = prev1, cur.
  4. Return prev1.

Why it works

Every decoding of the first i digits ends with a letter made of either the last digit or the last two digits. A single-digit letter must be 1 to 9, so a '0' cannot stand alone; a two-digit letter must be 10 to 26, which excludes leading zeros like "06". The two cases are disjoint, so their counts add. If both cases fail at some position, the count becomes 0 and stays 0, which correctly reports an invalid string.

Complexity

O(n) time, O(1) space.

Code

python
import random


def num_decodings(s):
    """'A'=1 ... 'Z'=26. ways(i) = ways(i-1) if s[i-1] != '0', plus ways(i-2) if s[i-2:i] is 10..26.
    O(n) time, O(1) space."""
    if not s:
        return 0
    prev2, prev1 = 1, 1                  # ways for "" and for the prefix so far
    if s[0] == "0":
        return 0
    for i in range(2, len(s) + 1):
        cur = 0
        if s[i - 1] != "0":
            cur += prev1
        if 10 <= int(s[i - 2:i]) <= 26:
            cur += prev2
        prev2, prev1 = prev1, cur
    return prev1


def brute(s):
    """Enumerate every split into 1- and 2-digit pieces."""
    if s == "":
        return 1
    total = 0
    if s[0] != "0":
        total += brute(s[1:])
        if len(s) >= 2 and int(s[:2]) <= 26:
            total += brute(s[2:])
    return total


if __name__ == "__main__":
    assert num_decodings("12") == 2                     # AB, L
    assert num_decodings("226") == 3                    # BBF, BZ, VF
    assert num_decodings("06") == 0 and num_decodings("100") == 0 and num_decodings("10") == 1
    assert num_decodings("") == 0
    rng = random.Random(86)
    for _ in range(2000):
        s = "".join(rng.choice("0122346789") for _ in range(rng.randint(1, 12)))
        assert num_decodings(s) == brute(s)
    print("all tests passed")

Save as b86_decode_ways.py and run python3 b86_decode_ways.py. It prints all tests passed (Python 3.13.5).

Edge cases

Leading zero (0). "00" or "30" (0). "10" and "20" (1 each). "100" (0, because the final 0 cannot attach). Long strings of 1s and 2s (Fibonacci growth). Empty string: this version returns 0 by convention; confirm with the interviewer.

Pattern

Fibonacci-style counting DP with validity conditions on each transition. Related: decode ways with a * wildcard (more cases, take a modulus), climbing stairs with broken steps, and counting valid splittings of a string under rules.

python
import random


def num_decodings(s):
    """'A'=1 ... 'Z'=26. ways(i) = ways(i-1) if s[i-1] != '0', plus ways(i-2) if s[i-2:i] is 10..26.
    O(n) time, O(1) space."""
    if not s:
        return 0
    prev2, prev1 = 1, 1                  # ways for "" and for the prefix so far
    if s[0] == "0":
        return 0
    for i in range(2, len(s) + 1):
        cur = 0
        if s[i - 1] != "0":
            cur += prev1
        if 10 <= int(s[i - 2:i]) <= 26:
            cur += prev2
        prev2, prev1 = prev1, cur
    return prev1


def brute(s):
    """Enumerate every split into 1- and 2-digit pieces."""
    if s == "":
        return 1
    total = 0
    if s[0] != "0":
        total += brute(s[1:])
        if len(s) >= 2 and int(s[:2]) <= 26:
            total += brute(s[2:])
    return total


if __name__ == "__main__":
    assert num_decodings("12") == 2                     # AB, L
    assert num_decodings("226") == 3                    # BBF, BZ, VF
    assert num_decodings("06") == 0 and num_decodings("100") == 0 and num_decodings("10") == 1
    assert num_decodings("") == 0
    rng = random.Random(86)
    for _ in range(2000):
        s = "".join(rng.choice("0122346789") for _ in range(rng.randint(1, 12)))
        assert num_decodings(s) == brute(s)
    print("all tests passed")

Rolling two-variable count with explicit zero rules, cross-checked against exhaustive splitting on random digit strings with many zeros.

Complexity

Time: O(n). Space: O(1). The wildcard variant has the same shape with more cases per step.

By level

Fresher: Derives the one-digit and two-digit cases and traces them on "226". Explains why "06" is not a valid letter.

Mid: Handles all zero cases, compresses to two variables, and tests strings like "100" and "2101". Extends to the wildcard variant with a modulus.

Senior: Treats the problem as counting accepted strings in a small automaton, which makes adding rules systematic. Discusses validating inputs early and the cost of listing all decodings.

Key points

  • Last letter is one digit or two digits
  • One digit must be 1 to 9
  • Two digits must be 10 to 26
  • Zero can only follow 1 or 2
  • Two variables are enough

Common mistakes

  • Treating '0' as a valid single letter
  • Accepting "06" as a two-digit letter
  • Wrong initial values for the empty prefix
  • Not returning 0 once the count drops to 0

Follow-ups

  • How do you handle a '*' that can be any digit 1 to 9?
  • How would you list the decodings?
  • How would you answer modulo 10^9 + 7 for long inputs?

Tips

  • List the zero cases before coding
  • Trace "226" and "100"
  • State the empty-string convention

Evaluation rubric

  • Correct recurrence
  • Correct zero handling
  • O(1) space
  • Tests tricky inputs
87.algorithms-0087Hardsenior

Longest palindromic subsequence: find the length of the longest subsequence that reads the same forwards and backwards, and use it to get the minimum insertions that make a string a palindrome.

Let dp[i][j] be the answer for s[i..j]. If s[i] == s[j], dp[i][j] = dp[i+1][j-1] + 2; otherwise dp[i][j] = max(dp[i+1][j], dp[i][j-1]). Filling i from the end and j forward takes O(n^2) time, and one row with a saved diagonal gives O(n) space. It also equals the LCS of s and its reverse, and the minimum insertions is n minus this length.

Full answer

Problem

Given a string s, return the length of its longest palindromic subsequence (characters keep their order but need not be adjacent). Then return the minimum number of insertions to make s a palindrome.

Example: "bbbab" gives 4 (bbbb); "cbbd" gives 2 (bb). "mbadm" needs 2 insertions (for example mbdadbm).

Constraints: 1 <= len(s) <= 1,000. Note that this differs from the longest palindromic substring, which must be contiguous.

Brute force

Check every subsequence, longest first, for being a palindrome: O(2^n * n).

Optimal approach

Interval DP over s[i..j]:

  • dp[i][i] = 1.
  • If s[i] == s[j]: dp[i][j] = dp[i+1][j-1] + 2.
  • Else: dp[i][j] = max(dp[i+1][j], dp[i][j-1]).

Fill i from n - 1 down to 0 and j from i + 1 up to n - 1 so that dp[i+1][*] is ready. To save space, keep one row and a diag variable holding dp[i+1][j-1] before it is overwritten.

Minimum insertions = n - LPS, because the characters outside the palindromic subsequence each need a mirror inserted.

Why it works

If the end characters match, some longest palindromic subsequence uses both of them as its outer pair (swapping them in never hurts), leaving the inside. If they differ, they cannot both be the outer pair, so at least one end is unused and the answer comes from dropping one end. Each case reduces to a shorter interval, so filling by increasing length covers all dependencies.

Complexity

O(n^2) time; O(n) space with one rolling row (O(n^2) if the subsequence itself must be rebuilt).

Code

python
import random
from itertools import combinations


def lps(s):
    """Longest palindromic subsequence (characters need not be contiguous).
    dp[i][j] over s[i..j]; rolled to one row. O(n^2) time, O(n) space."""
    n = len(s)
    if n == 0:
        return 0
    dp = [0] * n                          # dp[j] holds the value for the current i
    for i in range(n - 1, -1, -1):
        dp[i] = 1
        diag = 0                          # dp[i+1][j-1] from the previous row
        for j in range(i + 1, n):
            keep = dp[j]                  # dp[i+1][j] before overwrite
            if s[i] == s[j]:
                dp[j] = diag + 2
            else:
                dp[j] = max(dp[j], dp[j - 1])
            diag = keep
    return dp[n - 1]


def lps_via_lcs(s):
    """Equivalent: LCS of s and reversed s."""
    t = s[::-1]
    prev = [0] * (len(t) + 1)
    for a in s:
        cur = [0]
        for j, b in enumerate(t, 1):
            cur.append(prev[j - 1] + 1 if a == b else max(prev[j], cur[-1]))
        prev = cur
    return prev[-1]


def min_insertions_to_palindrome(s):
    return len(s) - lps(s)


def brute(s):
    for k in range(len(s), 0, -1):
        for idx in combinations(range(len(s)), k):
            sub = "".join(s[i] for i in idx)
            if sub == sub[::-1]:
                return k
    return 0


if __name__ == "__main__":
    assert lps("bbbab") == 4                            # bbbb
    assert lps("cbbd") == 2
    assert lps("") == 0 and lps("a") == 1
    assert min_insertions_to_palindrome("mbadm") == 2
    rng = random.Random(87)
    for _ in range(600):
        s = "".join(rng.choice("abc") for _ in range(rng.randint(0, 10)))
        assert lps(s) == lps_via_lcs(s) == brute(s)
    print("all tests passed")

Save as b87_longest_palindromic_subsequence.py and run python3 b87_longest_palindromic_subsequence.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty string (0). One character (1). All characters the same (n). All different (1). Do not confuse it with the substring problem, which uses expand-around-center and answers 3 for "bbbab" (bbb or bab) instead of 4.

Pattern

Interval DP on s[i..j], filled by increasing interval length or decreasing i. The same structure solves palindrome partitioning (minimum cuts), burst balloons, matrix chain multiplication and optimal game strategy on a row of coins. The LCS-with-reverse identity is a useful second derivation in interviews.

python
import random
from itertools import combinations


def lps(s):
    """Longest palindromic subsequence (characters need not be contiguous).
    dp[i][j] over s[i..j]; rolled to one row. O(n^2) time, O(n) space."""
    n = len(s)
    if n == 0:
        return 0
    dp = [0] * n                          # dp[j] holds the value for the current i
    for i in range(n - 1, -1, -1):
        dp[i] = 1
        diag = 0                          # dp[i+1][j-1] from the previous row
        for j in range(i + 1, n):
            keep = dp[j]                  # dp[i+1][j] before overwrite
            if s[i] == s[j]:
                dp[j] = diag + 2
            else:
                dp[j] = max(dp[j], dp[j - 1])
            diag = keep
    return dp[n - 1]


def lps_via_lcs(s):
    """Equivalent: LCS of s and reversed s."""
    t = s[::-1]
    prev = [0] * (len(t) + 1)
    for a in s:
        cur = [0]
        for j, b in enumerate(t, 1):
            cur.append(prev[j - 1] + 1 if a == b else max(prev[j], cur[-1]))
        prev = cur
    return prev[-1]


def min_insertions_to_palindrome(s):
    return len(s) - lps(s)


def brute(s):
    for k in range(len(s), 0, -1):
        for idx in combinations(range(len(s)), k):
            sub = "".join(s[i] for i in idx)
            if sub == sub[::-1]:
                return k
    return 0


if __name__ == "__main__":
    assert lps("bbbab") == 4                            # bbbb
    assert lps("cbbd") == 2
    assert lps("") == 0 and lps("a") == 1
    assert min_insertions_to_palindrome("mbadm") == 2
    rng = random.Random(87)
    for _ in range(600):
        s = "".join(rng.choice("abc") for _ in range(rng.randint(0, 10)))
        assert lps(s) == lps_via_lcs(s) == brute(s)
    print("all tests passed")

One-row interval DP with a saved diagonal, the LCS-with-reverse equivalent, minimum insertions, and an exhaustive subsequence check on random strings.

Complexity

Time: O(n^2). Space: O(n). Rebuilding the actual subsequence needs the full O(n^2) table or a second pass.

By level

Fresher: Writes the 2D interval table for small strings and explains the matching-ends case. Distinguishes the problem from the substring version.

Mid: Compresses to one row with a saved diagonal, derives minimum insertions, and explains the LCS equivalence. Rebuilds the subsequence from the full table.

Senior: Places the problem in the interval DP family and explains how fill order follows from dependencies. Discusses memory limits for long strings and when an O(n^2) table is too large.

Key points

  • Matching ends add 2 to the inside
  • Otherwise drop one end
  • Fill i downward, j upward
  • Equals LCS(s, reverse(s))
  • Insertions = n - LPS

Common mistakes

  • Confusing subsequence with substring
  • Wrong fill order so dp[i+1] is not ready
  • Losing the diagonal value in the rolling row
  • Off-by-one for intervals of length 2

Follow-ups

  • How would you rebuild the palindrome itself?
  • How do you find the minimum deletions instead of insertions?
  • How would you count distinct palindromic subsequences?

Tips

  • Clarify subsequence versus substring first
  • Explain the fill order
  • Mention the LCS identity

Evaluation rubric

  • Correct recurrence
  • Correct fill order
  • Space optimization
  • Connects to insertions
88.algorithms-0088Mediummid

Maximal square: find the area of the largest square containing only '1' cells in a binary matrix.

Let side[r][c] be the side of the largest all-1 square whose bottom-right corner is (r, c). For a '1' cell it is 1 + min(top, left, top-left); for a '0' cell it is 0. Track the maximum side and return its square. One rolling row with a saved diagonal gives O(R * C) time and O(C) space.

Full answer

Problem

Given an R x C matrix of '0' and '1', return the area of the largest square made only of '1' cells.

Example:

1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0

returns 4 (a 2 x 2 square).

Constraints: 1 <= R, C <= 300.

Brute force

For every cell as the top-left corner, grow the square while all cells inside are '1'. Checking a square of side k cell by cell costs O(k^2), so with k up to min(R, C) the total is O(R * C * min(R, C)^3); checking only the new border when growing brings it to O(R * C * min(R, C)^2).

Optimal approach

  • side[r][c] = 0 if the cell is '0'.
  • Otherwise side[r][c] = 1 + min(side[r-1][c], side[r][c-1], side[r-1][c-1]).
  • Answer: max(side) ** 2.

With one row of length C + 1 (a padding column of zeros): before overwriting row[c], save it as up; the previous up from column c - 1 is the diagonal.

Why it works

A square of side k ending at (r, c) exists exactly when squares of side k - 1 end at the cell above, the cell to the left and the cell diagonally up-left, and (r, c) itself is '1'. Those three overlapping squares together cover the k x k square except the corner. So the largest side is limited by the smallest of the three neighbours, plus one.

Complexity

O(R * C) time, O(C) extra space.

Code

python
import random


def maximal_square(matrix):
    """Area of the largest all-'1' square. side[r][c] = 1 + min(up, left, up-left).
    One rolling row: O(R * C) time, O(C) space."""
    if not matrix:
        return 0
    cols = len(matrix[0])
    row, best = [0] * (cols + 1), 0
    for r in matrix:
        diag = 0                          # side of the up-left neighbour
        for c in range(1, cols + 1):
            up = row[c]
            if r[c - 1] == "1":
                row[c] = 1 + min(up, row[c - 1], diag)
                best = max(best, row[c])
            else:
                row[c] = 0
            diag = up
    return best * best


def brute(matrix):
    if not matrix:
        return 0
    R, C, best = len(matrix), len(matrix[0]), 0
    for r in range(R):
        for c in range(C):
            k = 1
            while r + k <= R and c + k <= C and all(matrix[i][j] == "1" for i in range(r, r + k) for j in range(c, c + k)):
                best = max(best, k)
                k += 1
    return best * best


if __name__ == "__main__":
    m = ["10100", "10111", "11111", "10010"]
    assert maximal_square(m) == 4
    assert maximal_square(["01", "10"]) == 1 and maximal_square(["0"]) == 0 and maximal_square([]) == 0
    assert maximal_square(["111", "111", "111"]) == 9
    rng = random.Random(88)
    for _ in range(500):
        R, C = rng.randint(1, 7), rng.randint(1, 7)
        g = ["".join("1" if rng.random() < 0.7 else "0" for _ in range(C)) for _ in range(R)]
        assert maximal_square(g) == brute(g)
    print("all tests passed")

Save as b88_maximal_square.py and run python3 b88_maximal_square.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty matrix (0). No '1' cells (0). A full matrix (min(R, C) squared). Single row or column (1 if any '1'). Matrices given as integers instead of characters (adjust the comparison).

Pattern

Grid DP where a cell's value comes from its up, left and diagonal neighbours. Related: count all square submatrices of 1s (sum of all side values), largest rectangle of 1s (histogram with a monotonic stack per row), and longest common substring (diagonal-only dependency).

python
import random


def maximal_square(matrix):
    """Area of the largest all-'1' square. side[r][c] = 1 + min(up, left, up-left).
    One rolling row: O(R * C) time, O(C) space."""
    if not matrix:
        return 0
    cols = len(matrix[0])
    row, best = [0] * (cols + 1), 0
    for r in matrix:
        diag = 0                          # side of the up-left neighbour
        for c in range(1, cols + 1):
            up = row[c]
            if r[c - 1] == "1":
                row[c] = 1 + min(up, row[c - 1], diag)
                best = max(best, row[c])
            else:
                row[c] = 0
            diag = up
    return best * best


def brute(matrix):
    if not matrix:
        return 0
    R, C, best = len(matrix), len(matrix[0]), 0
    for r in range(R):
        for c in range(C):
            k = 1
            while r + k <= R and c + k <= C and all(matrix[i][j] == "1" for i in range(r, r + k) for j in range(c, c + k)):
                best = max(best, k)
                k += 1
    return best * best


if __name__ == "__main__":
    m = ["10100", "10111", "11111", "10010"]
    assert maximal_square(m) == 4
    assert maximal_square(["01", "10"]) == 1 and maximal_square(["0"]) == 0 and maximal_square([]) == 0
    assert maximal_square(["111", "111", "111"]) == 9
    rng = random.Random(88)
    for _ in range(500):
        R, C = rng.randint(1, 7), rng.randint(1, 7)
        g = ["".join("1" if rng.random() < 0.7 else "0" for _ in range(C)) for _ in range(R)]
        assert maximal_square(g) == brute(g)
    print("all tests passed")

Rolling row with a padding column and a saved diagonal, cross-checked against growing squares from every cell.

Complexity

Time: O(R * C). Space: O(C). Summing all side values counts every all-1 square submatrix with the same pass.

By level

Fresher: Writes the 2D table with the min-of-three rule and traces a small example. Returns the area rather than the side.

Mid: Rolls the table to one row with a saved diagonal and explains the overlapping-squares argument. Extends it to counting all squares.

Senior: Contrasts the square problem with the largest rectangle (histogram stack per row) and chooses the right tool. Discusses processing very large images row by row with O(C) memory.

Key points

  • side = 1 + min(up, left, diagonal) for a '1' cell
  • '0' cells reset to 0
  • Track the max side and square it
  • Rolling row plus saved diagonal
  • O(R * C)

Common mistakes

  • Returning the side instead of the area
  • Losing the diagonal value when rolling the row
  • Comparing integers with strings
  • Forgetting to reset to 0 on '0' cells

Follow-ups

  • How do you count all square submatrices of 1s?
  • How do you find the largest rectangle of 1s?
  • How would you handle a stream of rows that do not fit in memory?

Tips

  • Explain why the minimum of three neighbours bounds the side
  • Draw the overlapping squares
  • Return the area, not the side

Evaluation rubric

  • Correct recurrence
  • Correct area
  • Space optimization
  • Correct complexity
89.algorithms-0089Hardsenior

Burst balloons: maximise the coins earned by bursting all balloons, where bursting one pays the product of it and its current neighbours, using interval DP.

Pad the array with 1 at both ends. Let dp[l][r] be the best total for bursting every balloon strictly between l and r. Choose k as the last balloon burst in that interval: it then pays a[l] * a[k] * a[r], and the two sides are independent subproblems. dp[l][r] = max over k of dp[l][k] + a[l] * a[k] * a[r] + dp[k][r]. O(n^3) time and O(n^2) space.

Full answer

Problem

Given balloons with values nums, bursting balloon i earns left * nums[i] * right, where left and right are the current neighbours (or 1 past the ends). After bursting, neighbours become adjacent. Return the maximum coins from bursting all balloons.

Example: [3, 1, 5, 8] returns 167: burst 1 (315 = 15), then 5 (358 = 120), then 3 (138 = 24), then 8 (181 = 8).

Constraints: 1 <= n <= 300, values from 0 to 100.

Brute force

Try every bursting order: n! orders. Memoizing on the remaining tuple of balloons helps but still has 2^n states, as in the test reference.

Optimal approach

  1. a = [1] + nums + [1], size m = n + 2.
  2. dp[l][r] = best coins from bursting all balloons strictly between l and r (open interval); dp[l][l+1] = 0.
  3. For gap from 2 to m - 1, for each l with r = l + gap: dp[l][r] = max(dp[l][k] + a[l] * a[k] * a[r] + dp[k][r]) for k in l + 1..r - 1.
  4. Answer: dp[0][m-1].

Why it works

Choosing the first balloon to burst does not split the problem, because its neighbours change afterwards. Choosing the last balloon k in the interval does: while everything else between l and r is being burst, k is still present, so it acts as a fixed wall between the left part (l, k) and the right part (k, r). Those two parts never interact, and when k is finally burst its neighbours are exactly a[l] and a[r]. Trying every k as the last one covers all orders.

Complexity

O(n^3) time (about n^3 / 6 inner steps for n = 300, roughly 4.5 million, fine in Python) and O(n^2) space.

Code

python
import random
from functools import lru_cache


def max_coins(nums):
    """Burst balloons: bursting i earns left * nums[i] * right with current neighbours.
    Interval DP on which balloon is burst LAST inside (l, r). O(n^3) time, O(n^2) space."""
    a = [1] + [x for x in nums] + [1]
    n = len(a)
    dp = [[0] * n for _ in range(n)]       # dp[l][r]: best for balloons strictly between l and r
    for gap in range(2, n):
        for l in range(0, n - gap):
            r = l + gap
            best = 0
            for k in range(l + 1, r):      # k is the last balloon burst between l and r
                best = max(best, dp[l][k] + a[l] * a[k] * a[r] + dp[k][r])
            dp[l][r] = best
    return dp[0][n - 1]


def brute(nums):
    """Try every bursting order, memoised on the remaining tuple."""
    @lru_cache(maxsize=None)
    def go(rest):
        if not rest:
            return 0
        best = 0
        for i in range(len(rest)):
            left = rest[i - 1] if i > 0 else 1
            right = rest[i + 1] if i + 1 < len(rest) else 1
            best = max(best, left * rest[i] * right + go(rest[:i] + rest[i + 1:]))
        return best
    return go(tuple(nums))


if __name__ == "__main__":
    assert max_coins([3, 1, 5, 8]) == 167
    assert max_coins([1, 5]) == 10
    assert max_coins([]) == 0 and max_coins([7]) == 7
    rng = random.Random(89)
    for _ in range(300):
        a = [rng.randint(0, 9) for _ in range(rng.randint(0, 7))]
        assert max_coins(a) == brute(a)
    print("all tests passed")

Save as b89_burst_balloons.py and run python3 b89_burst_balloons.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty array (0). One balloon (its value). Zero-valued balloons (still need correct neighbour handling; some solutions remove them first, which is safe because bursting a 0 contributes 0 and they never help as neighbours). Large n where O(n^3) in a slow language needs care.

Pattern

Interval DP with a "last action splits the interval" insight. The same idea solves matrix chain multiplication, minimum cost to cut a stick, optimal binary search tree, polygon triangulation and merging stones. When the first choice does not separate subproblems, try the last.

python
import random
from functools import lru_cache


def max_coins(nums):
    """Burst balloons: bursting i earns left * nums[i] * right with current neighbours.
    Interval DP on which balloon is burst LAST inside (l, r). O(n^3) time, O(n^2) space."""
    a = [1] + [x for x in nums] + [1]
    n = len(a)
    dp = [[0] * n for _ in range(n)]       # dp[l][r]: best for balloons strictly between l and r
    for gap in range(2, n):
        for l in range(0, n - gap):
            r = l + gap
            best = 0
            for k in range(l + 1, r):      # k is the last balloon burst between l and r
                best = max(best, dp[l][k] + a[l] * a[k] * a[r] + dp[k][r])
            dp[l][r] = best
    return dp[0][n - 1]


def brute(nums):
    """Try every bursting order, memoised on the remaining tuple."""
    @lru_cache(maxsize=None)
    def go(rest):
        if not rest:
            return 0
        best = 0
        for i in range(len(rest)):
            left = rest[i - 1] if i > 0 else 1
            right = rest[i + 1] if i + 1 < len(rest) else 1
            best = max(best, left * rest[i] * right + go(rest[:i] + rest[i + 1:]))
        return best
    return go(tuple(nums))


if __name__ == "__main__":
    assert max_coins([3, 1, 5, 8]) == 167
    assert max_coins([1, 5]) == 10
    assert max_coins([]) == 0 and max_coins([7]) == 7
    rng = random.Random(89)
    for _ in range(300):
        a = [rng.randint(0, 9) for _ in range(rng.randint(0, 7))]
        assert max_coins(a) == brute(a)
    print("all tests passed")

Open-interval DP over a padded array, checked against an exhaustive memoized search over remaining balloons.

Complexity

Time: O(n^3). Space: O(n^2). Knuth-style speed-ups do not apply directly here; the cubic bound is standard.

By level

Fresher: Understands why trying all orders is too slow and follows the last-burst idea on a 3-balloon example. Fills a small table with guidance.

Mid: Writes the interval DP with padding and open intervals and explains the independence of the two sides. Recovers the order from choices.

Senior: Recognizes the last-action split across interval DP problems such as matrix chains and stick cutting, and explains when optimizations like Knuth's apply. Discusses reducing constant factors for n in the hundreds.

Key points

  • Pad with 1 at both ends
  • dp over open intervals (l, r)
  • Choose the last balloon burst, not the first
  • The last balloon's neighbours are a[l] and a[r]
  • O(n^3)

Common mistakes

  • Choosing the first balloon to burst and getting dependent subproblems
  • Using closed intervals and mixing up neighbour values
  • Wrong fill order by interval length
  • Forgetting the padding

Follow-ups

  • How does matrix chain multiplication use the same idea?
  • How would you recover the bursting order?
  • What changes if bursting pays only left * right?

Tips

  • Explain why the first choice fails
  • Define the interval as open
  • Fill by increasing gap

Evaluation rubric

  • Correct last-choice insight
  • Correct recurrence and fill order
  • Correct complexity
  • Edge cases
90.algorithms-0090Mediumfresher

Interval scheduling: select the largest number of non-overlapping intervals, and from that compute the fewest intervals to remove so the rest do not overlap.

Sort intervals by end time and take each interval whose start is at or after the end of the last one taken. Finishing earliest leaves the most room for the rest, which an exchange argument proves. That is O(n log n) for the sort and O(1) extra space. The minimum removals is n minus the number kept.

Full answer

Problem

Given intervals [start, end), return the maximum number that can be chosen with no two overlapping (touching at an endpoint is allowed). Then return the minimum number of intervals to remove so that the remaining ones do not overlap.

Example: [[1, 3], [2, 4], [3, 5], [6, 7]] allows 3 ([1,3], [3,5], [6,7]). [[1, 2], [2, 3], [3, 4], [1, 3]] needs 1 removal. Three copies of [1, 2] need 2 removals.

Constraints: up to 10^5 intervals; start < end.

Brute force

Try subsets from largest to smallest and check pairwise overlaps: O(2^n * n).

Optimal approach

  1. Sort by end time.
  2. last_end = -infinity, count = 0.
  3. For each (s, e): if s >= last_end, take it: count += 1, last_end = e.
  4. Removals = n - count.

Why it works

Let g be the interval with the earliest end. Take any optimal selection and replace its first interval with g: g ends no later, so it cannot overlap the second chosen interval, and the selection stays valid with the same size. So some optimal answer starts with g. Removing g and everything overlapping it leaves the same problem on the rest, and induction finishes the argument. Sorting by start time fails: one long early interval like [0, 10] can block three short ones, as the test shows.

Complexity

O(n log n) time for sorting, O(1) extra space beyond the sort.

Code

python
import random
from itertools import combinations


def max_non_overlapping(intervals):
    """Maximum number of pairwise non-overlapping [start, end) intervals.
    Greedy: sort by end, take every interval that starts at or after the last chosen end. O(n log n)."""
    count, last_end = 0, float("-inf")
    for s, e in sorted(intervals, key=lambda x: x[1]):
        if s >= last_end:
            count += 1
            last_end = e
    return count


def min_removals(intervals):
    """Fewest intervals to delete so the rest do not overlap."""
    return len(intervals) - max_non_overlapping(intervals)


def brute(intervals):
    for k in range(len(intervals), 0, -1):
        for combo in combinations(sorted(intervals), k):
            if all(combo[i][1] <= combo[i + 1][0] for i in range(k - 1)):
                return k
    return 0


if __name__ == "__main__":
    assert max_non_overlapping([[1, 3], [2, 4], [3, 5], [6, 7]]) == 3
    assert min_removals([[1, 2], [2, 3], [3, 4], [1, 3]]) == 1
    assert min_removals([[1, 2], [1, 2], [1, 2]]) == 2
    assert max_non_overlapping([]) == 0
    # sorting by start is wrong: one long early interval blocks three short ones
    assert max_non_overlapping([[0, 10], [1, 2], [3, 4], [5, 6]]) == 3
    rng = random.Random(90)
    for _ in range(800):
        iv = []
        for _ in range(rng.randint(0, 8)):
            s = rng.randint(0, 15)
            iv.append([s, s + rng.randint(1, 6)])
        assert max_non_overlapping(iv) == brute(iv)
    print("all tests passed")

Save as b90_interval_scheduling.py and run python3 b90_interval_scheduling.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty input (0). Identical intervals (keep one). Touching intervals [1,2] and [2,3] (compatible here; if the problem uses closed intervals, change >= to >). Negative coordinates.

Pattern

Earliest-finish-first greedy with an exchange argument. Related: minimum arrows to burst balloons (same sort, count groups), meeting rooms (can one person attend all), and weighted interval scheduling, where greedy fails and DP with binary search is needed.

python
import random
from itertools import combinations


def max_non_overlapping(intervals):
    """Maximum number of pairwise non-overlapping [start, end) intervals.
    Greedy: sort by end, take every interval that starts at or after the last chosen end. O(n log n)."""
    count, last_end = 0, float("-inf")
    for s, e in sorted(intervals, key=lambda x: x[1]):
        if s >= last_end:
            count += 1
            last_end = e
    return count


def min_removals(intervals):
    """Fewest intervals to delete so the rest do not overlap."""
    return len(intervals) - max_non_overlapping(intervals)


def brute(intervals):
    for k in range(len(intervals), 0, -1):
        for combo in combinations(sorted(intervals), k):
            if all(combo[i][1] <= combo[i + 1][0] for i in range(k - 1)):
                return k
    return 0


if __name__ == "__main__":
    assert max_non_overlapping([[1, 3], [2, 4], [3, 5], [6, 7]]) == 3
    assert min_removals([[1, 2], [2, 3], [3, 4], [1, 3]]) == 1
    assert min_removals([[1, 2], [1, 2], [1, 2]]) == 2
    assert max_non_overlapping([]) == 0
    # sorting by start is wrong: one long early interval blocks three short ones
    assert max_non_overlapping([[0, 10], [1, 2], [3, 4], [5, 6]]) == 3
    rng = random.Random(90)
    for _ in range(800):
        iv = []
        for _ in range(rng.randint(0, 8)):
            s = rng.randint(0, 15)
            iv.append([s, s + rng.randint(1, 6)])
        assert max_non_overlapping(iv) == brute(iv)
    print("all tests passed")

Sort by end and take compatible intervals; random sets are checked against exhaustive subset search, and a sort-by-start counterexample is included.

Complexity

Time: O(n log n). Space: O(1) extra besides sorting. Weighted versions need DP plus binary search, also O(n log n).

By level

Fresher: Sorts by end time and selects compatible intervals, tracing a small example. Shows why sorting by start can fail.

Mid: Gives the exchange argument and handles endpoint conventions. Connects the problem to minimum arrows and meeting room checks.

Senior: Contrasts with weighted interval scheduling and explains why greedy breaks there. Applies the idea to resource booking systems and explains how sorting dominates the cost at scale.

Key points

  • Sort by end time
  • Take an interval when it starts after the last chosen end
  • Exchange argument proves optimality
  • Removals = n - kept
  • Clarify open versus closed endpoints

Common mistakes

  • Sorting by start time
  • Sorting by length
  • Using > when touching intervals are allowed, or >= when they are not
  • Applying the greedy to weighted intervals

Follow-ups

  • How do you solve the weighted version?
  • What is the minimum number of points that hit every interval?
  • How many rooms are needed to hold all intervals?

Tips

  • State the exchange argument briefly
  • Show the sort-by-start counterexample
  • Ask about endpoint semantics

Evaluation rubric

  • Correct greedy
  • Proof or argument
  • Correct removal count
  • Correct complexity
91.algorithms-0091Mediummid

Merge overlapping intervals into a sorted list of disjoint intervals, and insert a new interval into an already merged list without sorting again.

Sort by start time, then walk the list: if the next interval starts at or before the end of the last merged block, extend that block's end to the larger end; otherwise start a new block. Sorting dominates at O(n log n). For inserting into an already sorted, disjoint list, copy the intervals that end before the new one, absorb those that overlap it, then copy the rest, all in O(n).

Full answer

Problem

Given closed intervals [start, end], merge all overlapping ones and return the result sorted by start. Follow-up: given a sorted list of disjoint intervals and a new interval, insert it and merge where needed.

Example: [[1,3], [2,6], [8,10], [15,18]] becomes [[1,6], [8,10], [15,18]]. [[1,4], [4,5]] becomes [[1,5]] because the endpoints touch. Inserting [4, 8] into [[1,2], [3,5], [6,7], [8,10]] gives [[1,2], [3,10]].

Constraints: up to 10^4 intervals; start <= end.

Brute force

Repeatedly scan all pairs and merge any two that overlap until nothing changes: O(n^2) per pass and up to n passes, O(n^3) worst case.

Optimal approach

Merge:

  1. Sort by start.
  2. For each [s, e]: if the output is non-empty and s <= out[-1][1], set out[-1][1] = max(out[-1][1], e); otherwise append [s, e].

Insert:

  1. Copy intervals with end < new_start.
  2. While intervals start at or before new_end, merge them into the new interval.
  3. Append the merged interval and then the remaining ones.

Why it works

After sorting by start, every interval that could overlap the current block must come right after it: an interval starting after the block's end, and everything after that, starts even later, so the block is final once a gap appears. Taking the max of ends handles intervals fully contained in the block. In the insert version, the input is already sorted and disjoint, so the three phases cover all positions exactly once.

Complexity

Merge: O(n log n) time for sorting, O(n) for the output. Insert: O(n) time, O(n) output.

Code

python
import random


def merge(intervals):
    """Merge overlapping closed intervals. Sort by start, extend the last block while it overlaps.
    O(n log n) time, O(n) output."""
    out = []
    for s, e in sorted(intervals):
        if out and s <= out[-1][1]:      # touching [1,3] and [3,5] merge because ends are inclusive
            out[-1][1] = max(out[-1][1], e)
        else:
            out.append([s, e])
    return out


def insert(intervals, new):
    """Insert into an already sorted, non-overlapping list in O(n) without re-sorting."""
    out, i, n = [], 0, len(intervals)
    s, e = new
    while i < n and intervals[i][1] < s:
        out.append(list(intervals[i]))
        i += 1
    while i < n and intervals[i][0] <= e:
        s, e = min(s, intervals[i][0]), max(e, intervals[i][1])
        i += 1
    out.append([s, e])
    return out + [list(x) for x in intervals[i:]]


def brute(intervals):
    """Mark covered half-steps on a number line (values are small ints)."""
    covered = set()
    for s, e in intervals:
        covered.update(range(2 * s, 2 * e + 1))
    out = []
    for x in sorted(covered):
        if out and x == out[-1][1] + 1:
            out[-1][1] = x
        else:
            out.append([x, x])
    return [[a // 2, b // 2] for a, b in out]


if __name__ == "__main__":
    assert merge([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]
    assert merge([[1, 4], [4, 5]]) == [[1, 5]]
    assert merge([[1, 4], [2, 3]]) == [[1, 4]]              # contained interval
    assert merge([]) == [] and merge([[5, 5]]) == [[5, 5]]
    assert insert([[1, 2], [3, 5], [6, 7], [8, 10]], [4, 8]) == [[1, 2], [3, 10]]
    rng = random.Random(91)
    for _ in range(1000):
        iv = []
        for _ in range(rng.randint(0, 8)):
            s = rng.randint(0, 20)
            iv.append([s, s + rng.randint(0, 5)])
        m = merge(iv)
        assert m == brute(iv)
        new = sorted([rng.randint(0, 25), rng.randint(0, 25)])
        assert insert(m, new) == merge(m + [new])
    print("all tests passed")

Save as b91_merge_intervals.py and run python3 b91_merge_intervals.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty input. Single interval. Contained intervals ([1,4] and [2,3]). Touching endpoints (merge for closed intervals; for half-open intervals use < instead of <=). Zero-length intervals like [5,5]. Do not modify the caller's lists when that matters (the code copies on insert).

Pattern

Sort then sweep, keeping one open block. Related: interval list intersections (two pointers), employee free time (merge then find gaps), calendar booking with a sorted structure, and summary ranges.

python
import random


def merge(intervals):
    """Merge overlapping closed intervals. Sort by start, extend the last block while it overlaps.
    O(n log n) time, O(n) output."""
    out = []
    for s, e in sorted(intervals):
        if out and s <= out[-1][1]:      # touching [1,3] and [3,5] merge because ends are inclusive
            out[-1][1] = max(out[-1][1], e)
        else:
            out.append([s, e])
    return out


def insert(intervals, new):
    """Insert into an already sorted, non-overlapping list in O(n) without re-sorting."""
    out, i, n = [], 0, len(intervals)
    s, e = new
    while i < n and intervals[i][1] < s:
        out.append(list(intervals[i]))
        i += 1
    while i < n and intervals[i][0] <= e:
        s, e = min(s, intervals[i][0]), max(e, intervals[i][1])
        i += 1
    out.append([s, e])
    return out + [list(x) for x in intervals[i:]]


def brute(intervals):
    """Mark covered half-steps on a number line (values are small ints)."""
    covered = set()
    for s, e in intervals:
        covered.update(range(2 * s, 2 * e + 1))
    out = []
    for x in sorted(covered):
        if out and x == out[-1][1] + 1:
            out[-1][1] = x
        else:
            out.append([x, x])
    return [[a // 2, b // 2] for a, b in out]


if __name__ == "__main__":
    assert merge([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]
    assert merge([[1, 4], [4, 5]]) == [[1, 5]]
    assert merge([[1, 4], [2, 3]]) == [[1, 4]]              # contained interval
    assert merge([]) == [] and merge([[5, 5]]) == [[5, 5]]
    assert insert([[1, 2], [3, 5], [6, 7], [8, 10]], [4, 8]) == [[1, 2], [3, 10]]
    rng = random.Random(91)
    for _ in range(1000):
        iv = []
        for _ in range(rng.randint(0, 8)):
            s = rng.randint(0, 20)
            iv.append([s, s + rng.randint(0, 5)])
        m = merge(iv)
        assert m == brute(iv)
        new = sorted([rng.randint(0, 25), rng.randint(0, 25)])
        assert insert(m, new) == merge(m + [new])
    print("all tests passed")

Sort-and-sweep merge and a linear insert, cross-checked against a number-line coverage brute force and against merge-after-append.

Complexity

Time: O(n log n) merge, O(n) insert. Space: O(n) output. For a stream of insertions, a balanced tree or sorted container keyed by start gives O(log n) per insert plus merged neighbours.

By level

Fresher: Sorts by start, merges with the last block, and handles containment with max. Traces the standard example.

Mid: Implements the linear insert, handles endpoint conventions, and explains why sorted order makes the sweep correct. Applies the method to free-time and intersection problems.

Senior: Discusses online interval sets with balanced trees, calendar systems with many users, and interval trees for overlap queries. Considers time zones and inclusive or exclusive boundaries in real scheduling data.

Key points

  • Sort by start
  • Extend the last block while starts are within its end
  • Use max of ends for contained intervals
  • Insert into a sorted list in three phases
  • Decide whether touching intervals merge

Common mistakes

  • Sorting by end time
  • Setting the end to the new interval's end instead of the max
  • Using < when closed intervals should merge on touch
  • Re-sorting for every insert

Follow-ups

  • How would you support many inserts and queries online?
  • How do you intersect two sorted interval lists?
  • How do you find free time slots across several calendars?

Tips

  • Ask whether touching intervals merge
  • Show the contained-interval case
  • Mention the O(n) insert without sorting

Evaluation rubric

  • Correct merge
  • Handles containment and touching
  • Correct insert
  • Correct complexity
92.algorithms-0092Mediummid

Jump game: decide whether you can reach the last index when each value is a maximum jump length, and find the fewest jumps needed when you can.

Track the farthest index reachable so far; if the loop ever reaches an index beyond it, you are stuck, otherwise the end is reachable. For the fewest jumps, treat the indices reachable with j jumps as a BFS layer: scan the current layer, track the farthest next reach, and count a jump each time the layer ends. Both run in O(n) time and O(1) space.

Full answer

Problem

Given nums where nums[i] is the maximum jump length from index i, start at index 0.

  • Part 1: return whether the last index is reachable.
  • Part 2: assuming it is reachable, return the minimum number of jumps.

Example: [2, 3, 1, 1, 4] is reachable in 2 jumps (0 to 1, then 1 to 4). [3, 2, 1, 0, 4] is not reachable, because every path lands on the 0 at index 3.

Constraints: 1 <= n <= 10^4, values from 0 to 1,000.

Brute force

BFS or DP over indices: from each index, try every jump length. dp[j] = min(dp[i] + 1) for all i that can reach j. That is O(n^2) in the worst case (up to O(n * max jump)).

Optimal approach

Reachability: far = 0; for each i, if i > far return False; else far = max(far, i + nums[i]). Return True.

Minimum jumps: keep end (last index reachable with the current number of jumps) and far (farthest reachable with one more jump). For i from 0 to n - 2: update far; when i == end, increment jumps and set end = far.

Why it works

Reachability: the set of reachable indices is always a prefix [0, far], because from any reachable index every shorter jump is also allowed. If index i is beyond far, nothing reachable can jump to it, and nothing beyond it is reachable either.

Minimum jumps: indices reachable with exactly j jumps form a contiguous block, and the next block ends at the farthest point reachable from the current block. Counting how many blocks are needed to cover the last index is exactly BFS by layers, done without a queue because each layer is a range.

Complexity

O(n) time and O(1) space for both parts.

Code

python
import random
from collections import deque


def can_reach_end(nums):
    """nums[i] is the maximum jump from i. Track the farthest reachable index. O(n), O(1)."""
    far = 0
    for i, x in enumerate(nums):
        if i > far:
            return False                 # stuck: i cannot be reached
        far = max(far, i + x)
    return True


def min_jumps(nums):
    """Fewest jumps to the last index (assumed reachable). Greedy BFS by layers: O(n)."""
    jumps, end, far = 0, 0, 0
    for i in range(len(nums) - 1):
        far = max(far, i + nums[i])
        if i == end:                     # finished the current layer: one more jump
            jumps += 1
            end = far
    return jumps


def brute_min(nums):
    """Plain BFS over indices, O(n^2) worst case. -1 when unreachable."""
    n = len(nums)
    dist = [-1] * n
    dist[0] = 0
    q = deque([0])
    while q:
        i = q.popleft()
        for j in range(i + 1, min(n, i + nums[i] + 1)):
            if dist[j] == -1:
                dist[j] = dist[i] + 1
                q.append(j)
    return dist[-1]


if __name__ == "__main__":
    assert can_reach_end([2, 3, 1, 1, 4]) and not can_reach_end([3, 2, 1, 0, 4])
    assert can_reach_end([0])                           # already at the end
    assert min_jumps([2, 3, 1, 1, 4]) == 2 and min_jumps([2, 3, 0, 1, 4]) == 2 and min_jumps([0]) == 0
    rng = random.Random(92)
    for _ in range(2000):
        a = [rng.randint(0, 4) for _ in range(rng.randint(1, 12))]
        b = brute_min(a)
        assert can_reach_end(a) == (b != -1)
        if b != -1:
            assert min_jumps(a) == b
    print("all tests passed")

Save as b92_jump_game.py and run python3 b92_jump_game.py. It prints all tests passed (Python 3.13.5).

Edge cases

Single element (reachable, 0 jumps). Zeros that can be jumped over. A zero at index 0 with n > 1 (unreachable). The loop for minimum jumps stops at n - 2 so that reaching the last index does not count an extra jump.

Pattern

Greedy over a reachable frontier, equivalent to BFS layers on an interval graph. Related: jump game with exact jumps in both directions (BFS), minimum taps to water a garden and video stitching (same layer greedy after converting to intervals), and frog jumps with costs (DP).

python
import random
from collections import deque


def can_reach_end(nums):
    """nums[i] is the maximum jump from i. Track the farthest reachable index. O(n), O(1)."""
    far = 0
    for i, x in enumerate(nums):
        if i > far:
            return False                 # stuck: i cannot be reached
        far = max(far, i + x)
    return True


def min_jumps(nums):
    """Fewest jumps to the last index (assumed reachable). Greedy BFS by layers: O(n)."""
    jumps, end, far = 0, 0, 0
    for i in range(len(nums) - 1):
        far = max(far, i + nums[i])
        if i == end:                     # finished the current layer: one more jump
            jumps += 1
            end = far
    return jumps


def brute_min(nums):
    """Plain BFS over indices, O(n^2) worst case. -1 when unreachable."""
    n = len(nums)
    dist = [-1] * n
    dist[0] = 0
    q = deque([0])
    while q:
        i = q.popleft()
        for j in range(i + 1, min(n, i + nums[i] + 1)):
            if dist[j] == -1:
                dist[j] = dist[i] + 1
                q.append(j)
    return dist[-1]


if __name__ == "__main__":
    assert can_reach_end([2, 3, 1, 1, 4]) and not can_reach_end([3, 2, 1, 0, 4])
    assert can_reach_end([0])                           # already at the end
    assert min_jumps([2, 3, 1, 1, 4]) == 2 and min_jumps([2, 3, 0, 1, 4]) == 2 and min_jumps([0]) == 0
    rng = random.Random(92)
    for _ in range(2000):
        a = [rng.randint(0, 4) for _ in range(rng.randint(1, 12))]
        b = brute_min(a)
        assert can_reach_end(a) == (b != -1)
        if b != -1:
            assert min_jumps(a) == b
    print("all tests passed")

Farthest-reach check and layer-counting jumps, cross-checked against BFS over indices on random arrays.

Complexity

Time: O(n). Space: O(1). The BFS reference is O(n * max jump).

By level

Fresher: Tracks the farthest reachable index and explains why falling behind it means failure. Traces both examples.

Mid: Writes the layer-based minimum jumps loop, explains the BFS equivalence, and handles the n - 2 boundary. Reconstructs the jump positions.

Senior: Maps covering problems (taps, video clips) to the same greedy and proves the contiguous-layer property. Discusses when greedy layer counting fails and BFS or DP is needed.

Key points

  • Reachable indices form a prefix [0, far]
  • Stuck when i > far
  • Indices reachable in j jumps form a range
  • Count a jump when the current range ends
  • Loop to n - 2 for the jump count

Common mistakes

  • Counting a jump on every index
  • Looping to n - 1 and adding an extra jump
  • Using DP O(n^2) when O(n) is expected
  • Missing the stuck check

Follow-ups

  • How would you return the actual jump positions?
  • What if jumps can go left or right by exactly nums[i]?
  • How does minimum taps to water a garden reduce to this?

Tips

  • Explain the prefix argument for reachability
  • Present the layers as implicit BFS
  • Test [0] and [1, 0, 1]

Evaluation rubric

  • Correct reachability
  • Correct minimum jumps
  • O(n)
  • Explains the layer idea
93.algorithms-0093Mediummid

Meeting rooms: given meeting time intervals, find the minimum number of rooms required so that no two overlapping meetings share a room.

Sort meetings by start time and keep a min-heap of end times for rooms in use. For each meeting, if the earliest-ending room is free by its start, reuse it (replace that end time); otherwise open a new room. The heap size at the end is the answer, in O(n log n) time. A sweep over sorted start and end events gives the same peak overlap.

Full answer

Problem

Given meetings [start, end), return the minimum number of rooms so that every meeting has a room for its whole duration. A meeting ending at time t frees the room for a meeting starting at t.

Example: [[0, 30], [5, 10], [15, 20]] needs 2 rooms; [[7, 10], [2, 4]] needs 1; [[1, 5], [5, 10]] needs 1.

Constraints: up to 10^4 meetings; times up to 10^6.

Brute force

For each time point (or each meeting start), count how many meetings are running and take the maximum: O(n * T) over a time range T, or O(n^2) over starts.

Optimal approach

Heap:

  1. Sort by start.
  2. For each meeting: if the heap's smallest end is <= start, replace it with this meeting's end; else push this end.
  3. Return the heap size.

Sweep: create events (start, +1) and (end, -1), sort (ends before starts at equal times, which tuple order gives because -1 < 1), and track the running sum and its maximum.

Why it works

The answer is at least the maximum number of meetings overlapping at one instant, because each needs its own room. The heap greedy never uses more: it opens a new room only when every room in use is busy at the new meeting's start, which means that many meetings overlap at that instant. Reusing the room that frees earliest is always safe because any free room works equally well for the current meeting.

Complexity

O(n log n) time for sorting and heap operations; O(n) space.

Code

python
import heapq
import random


def min_rooms(meetings):
    """Minimum rooms so no two overlapping [start, end) meetings share one.
    Sort by start, min-heap of end times of rooms in use. O(n log n)."""
    ends = []
    for s, e in sorted(meetings):
        if ends and ends[0] <= s:        # earliest-ending room is free again
            heapq.heapreplace(ends, e)
        else:
            heapq.heappush(ends, e)
    return len(ends)


def min_rooms_sweep(meetings):
    """Event sweep: +1 at start, -1 at end; ends sort before starts at the same time."""
    events = sorted([(s, 1) for s, _ in meetings] + [(e, -1) for _, e in meetings])
    cur = best = 0
    for _, delta in events:
        cur += delta
        best = max(best, cur)
    return best


def brute(meetings):
    """Max overlap at any integer time point."""
    if not meetings:
        return 0
    lo, hi = min(s for s, _ in meetings), max(e for _, e in meetings)
    return max(sum(s <= t < e for s, e in meetings) for t in range(lo, hi + 1))


if __name__ == "__main__":
    assert min_rooms([[0, 30], [5, 10], [15, 20]]) == 2
    assert min_rooms([[7, 10], [2, 4]]) == 1
    assert min_rooms([[1, 5], [5, 10]]) == 1           # back to back: same room
    assert min_rooms([]) == 0 and min_rooms_sweep([]) == 0
    rng = random.Random(93)
    for _ in range(1000):
        ms = []
        for _ in range(rng.randint(0, 10)):
            s = rng.randint(0, 20)
            ms.append([s, s + rng.randint(1, 8)])
        assert min_rooms(ms) == min_rooms_sweep(ms) == brute(ms)
    print("all tests passed")

Save as b93_meeting_rooms.py and run python3 b93_meeting_rooms.py. It prints all tests passed (Python 3.13.5).

Edge cases

No meetings (0). Back-to-back meetings (one room, thanks to <= and the event order). Identical meetings (one room each). Very long meetings overlapping everything.

Pattern

Peak overlap of intervals, computed with a min-heap of end times or a sweep line. Related: car pooling (capacity check with the same sweep), minimum platforms at a train station, CPU task scheduling across servers, and difference arrays when times are small integers.

python
import heapq
import random


def min_rooms(meetings):
    """Minimum rooms so no two overlapping [start, end) meetings share one.
    Sort by start, min-heap of end times of rooms in use. O(n log n)."""
    ends = []
    for s, e in sorted(meetings):
        if ends and ends[0] <= s:        # earliest-ending room is free again
            heapq.heapreplace(ends, e)
        else:
            heapq.heappush(ends, e)
    return len(ends)


def min_rooms_sweep(meetings):
    """Event sweep: +1 at start, -1 at end; ends sort before starts at the same time."""
    events = sorted([(s, 1) for s, _ in meetings] + [(e, -1) for _, e in meetings])
    cur = best = 0
    for _, delta in events:
        cur += delta
        best = max(best, cur)
    return best


def brute(meetings):
    """Max overlap at any integer time point."""
    if not meetings:
        return 0
    lo, hi = min(s for s, _ in meetings), max(e for _, e in meetings)
    return max(sum(s <= t < e for s, e in meetings) for t in range(lo, hi + 1))


if __name__ == "__main__":
    assert min_rooms([[0, 30], [5, 10], [15, 20]]) == 2
    assert min_rooms([[7, 10], [2, 4]]) == 1
    assert min_rooms([[1, 5], [5, 10]]) == 1           # back to back: same room
    assert min_rooms([]) == 0 and min_rooms_sweep([]) == 0
    rng = random.Random(93)
    for _ in range(1000):
        ms = []
        for _ in range(rng.randint(0, 10)):
            s = rng.randint(0, 20)
            ms.append([s, s + rng.randint(1, 8)])
        assert min_rooms(ms) == min_rooms_sweep(ms) == brute(ms)
    print("all tests passed")

Min-heap of end times and an event sweep, cross-checked against counting overlaps at every integer time.

Complexity

Time: O(n log n). Space: O(n). When times are small integers, a difference array gives O(n + T).

By level

Fresher: Sorts by start and uses a min-heap of end times, tracing a small example. Explains why back-to-back meetings share a room.

Mid: Gives the lower bound argument and the sweep alternative with correct tie order. Assigns room ids and handles the car pooling variant.

Senior: Discusses booking systems with room attributes and preferences, online allocation, and conflict checks with interval trees. Considers time zones and reservation buffers in real scheduling.

Key points

  • Rooms needed = maximum simultaneous meetings
  • Min-heap of end times
  • Reuse a room when its end <= new start
  • Sweep events with ends before starts at ties
  • O(n log n)

Common mistakes

  • Sorting by end time for the heap method
  • Using < instead of <= and opening a room for back-to-back meetings
  • Wrong tie order in the sweep
  • Counting only pairwise overlaps

Follow-ups

  • How would you also assign a specific room to each meeting?
  • How does car pooling with capacity use the same sweep?
  • How would you handle meetings arriving online?

Tips

  • State the lower bound argument
  • Clarify back-to-back semantics
  • Offer both heap and sweep

Evaluation rubric

  • Correct room count
  • Correct tie handling
  • Correctness argument
  • Correct complexity
94.algorithms-0094Mediummid

Gas station circuit: find the starting station from which a car can drive around a circular route once, given gas available and travel cost at each station.

If total gas is less than total cost, no start works. Otherwise scan once with a running tank; whenever the tank goes negative after station i, no station from the current start through i can be the start, so restart at i + 1 with an empty tank. The last restart point is the answer. O(n) time and O(1) space.

Full answer

Problem

There are n stations in a circle. Station i gives gas[i] and driving from i to i + 1 costs cost[i]. The tank starts empty. Return the index of a station from which you can complete the loop once, or -1 if impossible. If a solution exists, return the smallest valid index.

Example: gas = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2] returns 3. gas = [2, 3, 4], cost = [3, 4, 3] returns -1.

Constraints: 1 <= n <= 10^5; values from 0 to 10^4.

Brute force

Simulate from every start and stop when the tank goes negative: O(n^2).

Optimal approach

  1. If sum(gas) < sum(cost), return -1.
  2. start = 0, tank = 0. For each i: tank += gas[i] - cost[i]; if tank < 0, set start = i + 1, tank = 0.
  3. Return start.

Why it works

Skipping claim: if starting at s the tank first goes negative after station i, then no station k between s and i can be a start. Arriving at k from s, the tank was non-negative, so starting at k with an empty tank leaves you with no more fuel at every later point than the run from s had, and that run failed at i.

Existence claim: when total gas is at least total cost, the final start works. The segment from start to the end of the array keeps a non-negative tank by construction, and the deficit of the earlier part is covered by the surplus, because the total over the whole circle is non-negative. The cross-check confirms the result equals the first valid start found by simulation.

Complexity

O(n) time and O(1) space.

Code

python
import random


def can_complete_circuit(gas, cost):
    """Start index for one full clockwise loop, or -1. One pass, O(n), O(1).
    If the tank goes negative between start and i, no station in that range can be the start."""
    if sum(gas) < sum(cost):
        return -1
    start, tank = 0, 0
    for i in range(len(gas)):
        tank += gas[i] - cost[i]
        if tank < 0:
            start, tank = i + 1, 0
    return start


def brute(gas, cost):
    n = len(gas)
    for s in range(n):
        tank, ok = 0, True
        for k in range(n):
            i = (s + k) % n
            tank += gas[i] - cost[i]
            if tank < 0:
                ok = False
                break
        if ok:
            return s
    return -1


if __name__ == "__main__":
    assert can_complete_circuit([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]) == 3
    assert can_complete_circuit([2, 3, 4], [3, 4, 3]) == -1
    assert can_complete_circuit([5], [5]) == 0
    rng = random.Random(94)
    for _ in range(2000):
        n = rng.randint(1, 8)
        g = [rng.randint(0, 6) for _ in range(n)]
        c = [rng.randint(0, 6) for _ in range(n)]
        b = brute(g, c)
        got = can_complete_circuit(g, c)
        assert (got == -1) == (b == -1)
        if got != -1:
            assert brute(g[got:] + g[:got], c[got:] + c[:got]) == 0   # the returned start works
            assert got == b                                           # and it is the first valid start
    print("all tests passed")

Save as b94_gas_station.py and run python3 b94_gas_station.py. It prints all tests passed (Python 3.13.5).

Edge cases

Single station (valid if gas >= cost). Total exactly equal to cost (valid start exists). All stations with zero net. Many valid starts (this method returns the smallest).

Pattern

Greedy restart with a running sum, closely related to Kadane's algorithm and minimum prefix sums: the answer is the index right after the lowest point of the prefix sum of gas - cost. Similar ideas appear in circular subarray problems and in rebalancing tours.

python
import random


def can_complete_circuit(gas, cost):
    """Start index for one full clockwise loop, or -1. One pass, O(n), O(1).
    If the tank goes negative between start and i, no station in that range can be the start."""
    if sum(gas) < sum(cost):
        return -1
    start, tank = 0, 0
    for i in range(len(gas)):
        tank += gas[i] - cost[i]
        if tank < 0:
            start, tank = i + 1, 0
    return start


def brute(gas, cost):
    n = len(gas)
    for s in range(n):
        tank, ok = 0, True
        for k in range(n):
            i = (s + k) % n
            tank += gas[i] - cost[i]
            if tank < 0:
                ok = False
                break
        if ok:
            return s
    return -1


if __name__ == "__main__":
    assert can_complete_circuit([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]) == 3
    assert can_complete_circuit([2, 3, 4], [3, 4, 3]) == -1
    assert can_complete_circuit([5], [5]) == 0
    rng = random.Random(94)
    for _ in range(2000):
        n = rng.randint(1, 8)
        g = [rng.randint(0, 6) for _ in range(n)]
        c = [rng.randint(0, 6) for _ in range(n)]
        b = brute(g, c)
        got = can_complete_circuit(g, c)
        assert (got == -1) == (b == -1)
        if got != -1:
            assert brute(g[got:] + g[:got], c[got:] + c[:got]) == 0   # the returned start works
            assert got == b                                           # and it is the first valid start
    print("all tests passed")

Total check plus one pass with restarts, cross-checked against full simulation from every start, including that the returned start is the first valid one.

Complexity

Time: O(n). Space: O(1). Equivalent to choosing the index after the minimum prefix sum of gas - cost.

By level

Fresher: Simulates from one start and then explains why a failure at i rules out every station in between. Writes the one-pass version with the total check.

Mid: Argues both the skipping and existence claims and relates them to minimum prefix sums. Handles multiple valid starts.

Senior: Generalizes to tank capacity limits and circular route planning, and discusses when greedy restarts stop working. Connects the prefix-sum view to circular buffer and balancing problems.

Key points

  • Total gas < total cost means -1
  • Restart after any station where the tank goes negative
  • Skipped stations cannot be starts
  • The last restart is the answer
  • One pass, O(n) time and O(1) space

Common mistakes

  • Simulating from every start (O(n^2))
  • Forgetting the total check
  • Resetting start to i instead of i + 1
  • Assuming the answer is unique

Follow-ups

  • How would you find all valid starts?
  • What if the tank has a maximum capacity?
  • How is this related to minimum prefix sums?

Tips

  • Prove the skipping claim in words
  • State the total condition first
  • Mention the prefix-sum view

Evaluation rubric

  • Correct algorithm
  • Correctness argument
  • Handles impossibility
  • Correct complexity
95.algorithms-0095Easyfresher

Bit manipulation basics: get, set, clear and toggle a bit, test for a power of two, count set bits, and find the single number when every other value appears twice.

Use masks: get with (x >> i) & 1, set with x | (1 << i), clear with x & ~(1 << i), toggle with x ^ (1 << i). x & (x - 1) clears the lowest set bit, so x is a power of two when x > 0 and x & (x - 1) == 0, and repeating it counts set bits. XOR of all values cancels pairs and leaves the single number in O(n) time and O(1) space.

Full answer

Problem

Implement the basic bit operations on non-negative integers:

  • get_bit, set_bit, clear_bit, toggle_bit for bit i.
  • is_power_of_two(x), popcount(x) and lowest_set_bit(x).
  • single_number(nums): every value appears exactly twice except one; return it.

Example: for x = 0b1010 (10), bit 1 is 1 and bit 0 is 0; setting bit 0 gives 11; clearing bit 3 gives 2. 64 is a power of two, 12 is not. single_number([4, 1, 2, 1, 2]) is 4.

Constraints: 32-bit values for the classic version; Python integers are unbounded, so negative numbers behave as infinite two's complement.

Brute force

Convert to a binary string and inspect characters: O(bits) per operation with string allocation. For single number, a hash map of counts uses O(n) space.

Optimal approach

  • (x >> i) & 1 reads bit i.
  • x | (1 << i) sets it, x & ~(1 << i) clears it, x ^ (1 << i) flips it.
  • x & (x - 1) removes the lowest set bit. Power of two: x > 0 and x & (x - 1) == 0.
  • Popcount (Kernighan): repeat x &= x - 1 and count steps.
  • Lowest set bit: x & -x.
  • Single number: XOR every value.

Why it works

Subtracting 1 flips the lowest set bit to 0 and all lower zeros to 1, so AND with the original clears exactly that bit. A power of two has a single set bit, so clearing it gives 0. In two's complement, -x is ~x + 1, which keeps the lowest set bit and flips everything above it, so x & -x isolates it. XOR is associative and commutative with a ^ a = 0 and a ^ 0 = a, so paired values cancel in any order.

Complexity

Each mask operation is O(1). Kernighan's popcount is O(number of set bits). Single number is O(n) time and O(1) space. Python 3.10+ also offers int.bit_count().

Code

python
import random


def get_bit(x, i):
    return (x >> i) & 1


def set_bit(x, i):
    return x | (1 << i)


def clear_bit(x, i):
    return x & ~(1 << i)


def toggle_bit(x, i):
    return x ^ (1 << i)


def is_power_of_two(x):
    """A power of two has exactly one set bit; x & (x - 1) clears the lowest set bit."""
    return x > 0 and x & (x - 1) == 0


def popcount(x):
    """Brian Kernighan: loop once per set bit. Non-negative x."""
    n = 0
    while x:
        x &= x - 1
        n += 1
    return n


def lowest_set_bit(x):
    return x & -x


def single_number(nums):
    """Every value appears twice except one. a ^ a = 0 and a ^ 0 = a. O(n), O(1)."""
    out = 0
    for v in nums:
        out ^= v
    return out


if __name__ == "__main__":
    x = 0b1010
    assert get_bit(x, 1) == 1 and get_bit(x, 0) == 0
    assert set_bit(x, 0) == 0b1011 and clear_bit(x, 3) == 0b0010 and toggle_bit(x, 1) == 0b1000
    assert [v for v in range(70) if is_power_of_two(v)] == [1, 2, 4, 8, 16, 32, 64]
    assert lowest_set_bit(12) == 4
    assert single_number([4, 1, 2, 1, 2]) == 4 and single_number([-3, 7, 7]) == -3
    rng = random.Random(95)
    for _ in range(2000):
        v = rng.randint(0, 1 << 40)
        assert popcount(v) == bin(v).count("1")
        assert lowest_set_bit(v) == (0 if v == 0 else 1 << (len(bin(v)) - len(bin(v).rstrip("0"))))
    print("all tests passed")

Save as b95_bit_basics.py and run python3 b95_bit_basics.py. It prints all tests passed (Python 3.13.5).

Edge cases

x = 0 (not a power of two; popcount 0; lowest set bit 0). Negative numbers in Python (use a mask such as & 0xFFFFFFFF to emulate 32-bit). Shifting by 31 or more in fixed-width languages (undefined or sign issues in C and Java). Operator precedence: in Python x & x - 1 already means x & (x - 1), but parentheses make it clear.

Pattern

Masks and XOR cancellation. These building blocks appear in subset enumeration with bitmasks, permission flags, Bloom filters, Gray codes, and DP over subsets.

python
import random


def get_bit(x, i):
    return (x >> i) & 1


def set_bit(x, i):
    return x | (1 << i)


def clear_bit(x, i):
    return x & ~(1 << i)


def toggle_bit(x, i):
    return x ^ (1 << i)


def is_power_of_two(x):
    """A power of two has exactly one set bit; x & (x - 1) clears the lowest set bit."""
    return x > 0 and x & (x - 1) == 0


def popcount(x):
    """Brian Kernighan: loop once per set bit. Non-negative x."""
    n = 0
    while x:
        x &= x - 1
        n += 1
    return n


def lowest_set_bit(x):
    return x & -x


def single_number(nums):
    """Every value appears twice except one. a ^ a = 0 and a ^ 0 = a. O(n), O(1)."""
    out = 0
    for v in nums:
        out ^= v
    return out


if __name__ == "__main__":
    x = 0b1010
    assert get_bit(x, 1) == 1 and get_bit(x, 0) == 0
    assert set_bit(x, 0) == 0b1011 and clear_bit(x, 3) == 0b0010 and toggle_bit(x, 1) == 0b1000
    assert [v for v in range(70) if is_power_of_two(v)] == [1, 2, 4, 8, 16, 32, 64]
    assert lowest_set_bit(12) == 4
    assert single_number([4, 1, 2, 1, 2]) == 4 and single_number([-3, 7, 7]) == -3
    rng = random.Random(95)
    for _ in range(2000):
        v = rng.randint(0, 1 << 40)
        assert popcount(v) == bin(v).count("1")
        assert lowest_set_bit(v) == (0 if v == 0 else 1 << (len(bin(v)) - len(bin(v).rstrip("0"))))
    print("all tests passed")

Mask helpers, Kernighan popcount, lowest set bit and XOR single number, with random checks against bin().count and string-based lowest bit.

Complexity

Time: O(1) per mask operation; O(n) for single number. Space: O(1). Kernighan's loop runs once per set bit; int.bit_count() is a built-in alternative.

By level

Fresher: Writes get, set, clear and toggle with masks and explains each on a 4-bit example. Solves single number with XOR.

Mid: Explains why x & (x - 1) and x & -x work using two's complement and handles 0 and negatives. Extends XOR to the two-singles variant.

Senior: Discusses fixed-width pitfalls across languages, hardware popcount instructions, and bit-packed data structures such as bitsets and Bloom filters. Weighs readability against speed for bit tricks in production code.

Key points

  • Shift and mask to read or write bit i
  • x & (x - 1) clears the lowest set bit
  • Power of two: x > 0 and x & (x - 1) == 0
  • x & -x isolates the lowest set bit
  • XOR cancels pairs

Common mistakes

  • Forgetting x > 0 in the power-of-two test
  • Precedence bugs in languages where & binds looser than ==
  • Ignoring sign behaviour of negative numbers in Python
  • Using a hash map when XOR solves it in O(1) space

Follow-ups

  • How would you swap two variables without a temporary?
  • How do you find two values that each appear once while all others appear twice?
  • How are bit flags used for permissions?

Tips

  • Say each mask out loud with a 4-bit example
  • Mention Python's unbounded integers
  • Explain XOR cancellation with a short list

Evaluation rubric

  • Correct masks
  • Correct power-of-two and popcount
  • XOR solution
  • Edge cases with 0 and negatives
96.algorithms-0096Easyfresher

Counting bits: return an array with the number of 1 bits in every integer from 0 to n in linear time.

Reuse earlier answers: shifting i right by one drops its lowest bit, so bits[i] = bits[i >> 1] + (i & 1). Another recurrence removes the lowest set bit: bits[i] = bits[i & (i - 1)] + 1. Either fills the array in O(n) time, compared with O(n log n) when each number is counted separately.

Full answer

Problem

Given n, return bits of length n + 1 where bits[i] is the number of 1s in the binary representation of i.

Example: n = 5 gives [0, 1, 1, 2, 1, 2].

Constraints: 0 <= n <= 10^5. Target O(n) time without a built-in popcount.

Brute force

Count bits for each i separately (string conversion, or a loop over bits): O(log i) each, O(n log n) total.

Optimal approach

bits[0] = 0. For i from 1 to n:

  • Shift recurrence: bits[i] = bits[i >> 1] + (i & 1).
  • Or lowest-bit recurrence: bits[i] = bits[i & (i - 1)] + 1.

Both refer only to smaller indices, which are already filled.

Why it works

i >> 1 is i with its lowest bit removed, so its count differs from i's by exactly that bit, i & 1. Similarly, i & (i - 1) is i with its lowest set bit cleared, which has exactly one fewer 1. Both values are smaller than i, so the array can be filled in increasing order.

Complexity

O(n) time and O(n) space for the output.

Code

python
def count_bits(n):
    """Set-bit counts for 0..n. bits[i] = bits[i >> 1] + (i & 1). O(n) time."""
    bits = [0] * (n + 1)
    for i in range(1, n + 1):
        bits[i] = bits[i >> 1] + (i & 1)
    return bits


def count_bits_low(n):
    """Alternative recurrence: dropping the lowest set bit gives a smaller number."""
    bits = [0] * (n + 1)
    for i in range(1, n + 1):
        bits[i] = bits[i & (i - 1)] + 1
    return bits


def brute(n):
    """O(n log n): count each number separately."""
    return [bin(i).count("1") for i in range(n + 1)]


if __name__ == "__main__":
    assert count_bits(2) == [0, 1, 1]
    assert count_bits(5) == [0, 1, 1, 2, 1, 2]
    assert count_bits(0) == [0]
    for n in (1, 7, 64, 1000, 4097):
        assert count_bits(n) == count_bits_low(n) == brute(n)
    print("all tests passed")

Save as b96_counting_bits.py and run python3 b96_counting_bits.py. It prints all tests passed (Python 3.13.5).

Edge cases

n = 0 returns [0]. Powers of two have count 1. Values just below a power of two (all ones) have the largest counts.

Pattern

DP over integers using bit relations: the answer for i comes from a smaller number obtained by a bit operation. The same idea powers subset-sum-over-masks DP, Gray code generation, and counting set bits over a range by bit position.

python
def count_bits(n):
    """Set-bit counts for 0..n. bits[i] = bits[i >> 1] + (i & 1). O(n) time."""
    bits = [0] * (n + 1)
    for i in range(1, n + 1):
        bits[i] = bits[i >> 1] + (i & 1)
    return bits


def count_bits_low(n):
    """Alternative recurrence: dropping the lowest set bit gives a smaller number."""
    bits = [0] * (n + 1)
    for i in range(1, n + 1):
        bits[i] = bits[i & (i - 1)] + 1
    return bits


def brute(n):
    """O(n log n): count each number separately."""
    return [bin(i).count("1") for i in range(n + 1)]


if __name__ == "__main__":
    assert count_bits(2) == [0, 1, 1]
    assert count_bits(5) == [0, 1, 1, 2, 1, 2]
    assert count_bits(0) == [0]
    for n in (1, 7, 64, 1000, 4097):
        assert count_bits(n) == count_bits_low(n) == brute(n)
    print("all tests passed")

Two O(n) recurrences checked against bin(i).count('1') for several n.

Complexity

Time: O(n). Space: O(n) output. The brute force is O(n log n).

By level

Fresher: Writes the shift recurrence and explains it with small binary numbers. Returns an array of length n + 1.

Mid: Gives both recurrences with explanations and computes total set bits from 1 to n by bit position in O(log n). Discusses built-in popcount availability.

Senior: Relates bit-based DP to subset DP and hardware popcount support, and discusses vectorized popcount for large bitsets. Chooses between table lookups and instructions for performance-critical code.

Key points

  • bits[i] = bits[i >> 1] + (i & 1)
  • bits[i] = bits[i & (i - 1)] + 1
  • Both use smaller indices
  • O(n) total
  • bits[0] = 0

Common mistakes

  • Off-by-one array length (needs n + 1)
  • Using a per-number loop and missing the O(n) target
  • Using built-in popcount when the interviewer asked not to
  • Wrong base case

Follow-ups

  • How do you count total set bits from 1 to n without listing them?
  • How would you generate a Gray code sequence?
  • What changes for 64-bit ranges?

Tips

  • Explain the shift relation with a 3-bit example
  • Mention the second recurrence
  • Return n + 1 values

Evaluation rubric

  • Correct recurrence
  • O(n)
  • Correct base case
  • Explains why it works
97.algorithms-0097Easyfresher

Use bits to find the missing number in a list containing all but one of the values 0 to n, and to enumerate every subset of a small list with bitmasks.

XOR all indices 0..n with all values: every present number appears twice and cancels, leaving the missing one, in O(n) time and O(1) space with no overflow risk. For subsets, each integer mask from 0 to 2^n - 1 picks the items whose bit is set, giving all 2^n subsets in O(n * 2^n).

Full answer

Problem

Part 1: nums contains n distinct numbers from 0..n with exactly one missing; return the missing number.

Part 2: return all subsets of a list of n distinct items.

Example: [3, 0, 1] is missing 2; [0, 1] is missing 2; [1] is missing 0. Subsets of [1, 2, 3] in mask order are [], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3].

Constraints: up to 10^4 numbers for part 1; n <= 16 for part 2 (65,536 subsets).

Brute force

Part 1: sort and scan for the gap (O(n log n)), or build a set and check each value (O(n) time, O(n) space). The sum formula n(n+1)/2 - sum(nums) is O(1) space but can overflow in fixed-width languages.

Part 2: recursive include or exclude for each item (also O(n * 2^n), but more code).

Optimal approach

Part 1: start with x = n; for each index i and value v, x ^= i ^ v. Return x.

Part 2: for mask in range(1 << n), include items[i] when (mask >> i) & 1 is 1.

Why it works

Part 1: the XOR covers every number in 0..n once from the indices (plus n), and every present number once more from the values. Present numbers cancel in pairs, leaving the missing one.

Part 2: the integers 0..2^n - 1 are in one-to-one correspondence with subsets of n items, bit i saying whether item i is chosen. Enumerating every integer enumerates every subset exactly once.

Complexity

Part 1: O(n) time, O(1) space. Part 2: O(n * 2^n) time and output size.

Code

python
import random
from itertools import combinations


def missing_number(nums):
    """nums holds n distinct values from 0..n with one missing. XOR all indices and values."""
    x = len(nums)
    for i, v in enumerate(nums):
        x ^= i ^ v
    return x


def subsets_bitmask(items):
    """All 2^n subsets: bit i of mask says whether items[i] is in. O(n * 2^n)."""
    n = len(items)
    return [[items[i] for i in range(n) if mask >> i & 1] for mask in range(1 << n)]


def brute_missing(nums):
    return (set(range(len(nums) + 1)) - set(nums)).pop()


if __name__ == "__main__":
    assert missing_number([3, 0, 1]) == 2 and missing_number([0, 1]) == 2 and missing_number([1]) == 0
    assert subsets_bitmask([1, 2, 3]) == [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
    assert subsets_bitmask([]) == [[]]
    rng = random.Random(97)
    for _ in range(500):
        n = rng.randint(1, 50)
        vals = list(range(n + 1))
        vals.remove(rng.randint(0, n))
        rng.shuffle(vals)
        assert missing_number(vals) == brute_missing(vals)
    for n in range(0, 8):
        items = list(range(n))
        got = sorted(map(tuple, subsets_bitmask(items)))
        want = sorted(c for k in range(n + 1) for c in combinations(items, k))
        assert got == want
    print("all tests passed")

Save as b97_missing_number_subsets.py and run python3 b97_missing_number_subsets.py. It prints all tests passed (Python 3.13.5).

Edge cases

Missing 0 or missing n. Single element. Part 2 with an empty list (one subset, the empty one). Large n in part 2: 2^n explodes, so masks are only practical up to about 20 items.

Pattern

XOR cancellation and masks as sets. Related: find the duplicate and the missing number together, single number variants, bitmask DP (TSP, assignment), and iterating submasks of a mask with sub = (sub - 1) & mask.

python
import random
from itertools import combinations


def missing_number(nums):
    """nums holds n distinct values from 0..n with one missing. XOR all indices and values."""
    x = len(nums)
    for i, v in enumerate(nums):
        x ^= i ^ v
    return x


def subsets_bitmask(items):
    """All 2^n subsets: bit i of mask says whether items[i] is in. O(n * 2^n)."""
    n = len(items)
    return [[items[i] for i in range(n) if mask >> i & 1] for mask in range(1 << n)]


def brute_missing(nums):
    return (set(range(len(nums) + 1)) - set(nums)).pop()


if __name__ == "__main__":
    assert missing_number([3, 0, 1]) == 2 and missing_number([0, 1]) == 2 and missing_number([1]) == 0
    assert subsets_bitmask([1, 2, 3]) == [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
    assert subsets_bitmask([]) == [[]]
    rng = random.Random(97)
    for _ in range(500):
        n = rng.randint(1, 50)
        vals = list(range(n + 1))
        vals.remove(rng.randint(0, n))
        rng.shuffle(vals)
        assert missing_number(vals) == brute_missing(vals)
    for n in range(0, 8):
        items = list(range(n))
        got = sorted(map(tuple, subsets_bitmask(items)))
        want = sorted(c for k in range(n + 1) for c in combinations(items, k))
        assert got == want
    print("all tests passed")

XOR missing number checked against a set difference on shuffled inputs, and mask-based subsets checked against itertools.combinations.

Complexity

Time: O(n) missing number; O(n * 2^n) subsets. Space: O(1) missing number; O(n * 2^n) output. The sum formula is also O(1) space in Python, where integers do not overflow.

By level

Fresher: Solves the missing number with XOR and explains cancellation on a small list. Lists subsets by counting masks.

Mid: Compares XOR, sum and set methods on space and overflow. Iterates submasks and explains the 2^n limit.

Senior: Applies masks to DP over subsets and discusses limits, meet-in-the-middle for n around 40, and bitset representations for large sets. Estimates 2^n work before committing to a mask-based method.

Key points

  • XOR indices and values to cancel present numbers
  • Start with x = n
  • Mask bit i selects item i
  • 2^n masks enumerate all subsets
  • Practical for n up to about 20

Common mistakes

  • Forgetting to include n in the XOR
  • Overflow with the sum formula in fixed-width languages
  • Using masks for n = 40
  • Off-by-one in the mask range

Follow-ups

  • How would you find both a duplicate and a missing number?
  • How do you iterate all submasks of a mask?
  • How do subsets become a DP over masks?

Tips

  • Explain cancellation with a 4-element example
  • Mention the overflow risk of the sum formula
  • Draw mask bits next to items

Evaluation rubric

  • Correct XOR method
  • Correct subset enumeration
  • Correct complexity
  • Edge cases
98.algorithms-0098Hardsenior

Single number when every other value appears three times: find the one value that appears once in O(n) time and O(1) extra space.

XOR alone fails because three copies do not cancel. Count each bit position modulo 3: the bits left over belong to the single number. Two integers can hold that counter for all 32 positions at once: ones and twos, updated with ones = (ones ^ v) & ~twos and twos = (twos ^ v) & ~ones. At the end ones holds the answer. O(n) time, O(1) space.

Full answer

Problem

In nums, every value appears exactly three times except one, which appears once. Return that value using O(1) extra space.

Example: [2, 2, 3, 2] returns 3; [0, 1, 0, 1, 0, 1, 99] returns 99; negative values must work too.

Constraints: up to 3 * 10^4 numbers; values are 32-bit signed integers.

Brute force

Count occurrences with a hash map and return the value with count 1: O(n) time but O(n) space. Sorting and scanning in groups of three is O(n log n).

Optimal approach

Per-bit counting: for each bit position b in 0..31, sum the b-th bits of all numbers; if the sum mod 3 is 1, set bit b in the answer. Convert from 32-bit two's complement at the end. O(32n).

Bit state machine: keep ones and twos.

  • ones = (ones ^ v) & ~twos
  • twos = (twos ^ v) & ~ones

After all values, ones is the answer.

Why it works

For each bit position, the bits of the triple values contribute a multiple of 3, so the count modulo 3 equals that bit of the single value. The state machine tracks that count per bit: a bit is in ones when its count is 1 mod 3 and in twos when it is 2 mod 3. On a new 1 bit the state moves 0 to 1 to 2 to 0: the first line adds the bit to ones unless it is already in twos; the second adds it to twos only if it just left ones; a third occurrence clears both. All 32 positions update in parallel with word operations. In Python, negative numbers behave as infinitely sign-extended, and the same identities hold, so ones comes out with the right sign.

Complexity

O(n) time and O(1) space for the state machine; O(32n) for per-bit counting.

Code

python
import random
from collections import Counter


def single_number_thrice(nums):
    """Every value appears three times except one, which appears once. O(n) time, O(1) space.
    `ones` holds bits seen 1 (mod 3) times, `twos` bits seen 2 (mod 3) times."""
    ones = twos = 0
    for v in nums:
        ones = (ones ^ v) & ~twos
        twos = (twos ^ v) & ~ones
    return ones


def single_number_bitcount(nums):
    """Per-bit counting mod 3 over 32 bits, then convert back from two's complement."""
    out = 0
    for b in range(32):
        if sum((v >> b) & 1 for v in nums) % 3:
            out |= 1 << b
    return out - (1 << 32) if out >= 1 << 31 else out


def brute(nums):
    return next(v for v, c in Counter(nums).items() if c == 1)


if __name__ == "__main__":
    assert single_number_thrice([2, 2, 3, 2]) == 3
    assert single_number_thrice([0, 1, 0, 1, 0, 1, 99]) == 99
    assert single_number_thrice([-2, -2, 1, 1, 4, 1, 4, 4, -5, -2]) == -5   # negatives work too
    rng = random.Random(98)
    for _ in range(1000):
        vals = rng.sample(range(-1000, 1000), rng.randint(1, 8))
        nums = [vals[0]] + [v for v in vals[1:] for _ in range(3)]
        rng.shuffle(nums)
        assert single_number_thrice(nums) == single_number_bitcount(nums) == brute(nums)
    print("all tests passed")

Save as b98_single_number_thrice.py and run python3 b98_single_number_thrice.py. It prints all tests passed (Python 3.13.5).

Edge cases

The single value is negative or zero. Only one element. Values at 32-bit limits (per-bit counting needs the two's complement fix in Python; the state machine does not). If the problem changes to "appears twice" for the single, return twos instead.

Pattern

Counting bits modulo k with a small state machine encoded in words. The general rule works for any k with ceil(log2 k) state words. Related: single number with all others appearing twice (XOR), two singles (XOR then split by a set bit), and bitwise digital-logic design of counters.

python
import random
from collections import Counter


def single_number_thrice(nums):
    """Every value appears three times except one, which appears once. O(n) time, O(1) space.
    `ones` holds bits seen 1 (mod 3) times, `twos` bits seen 2 (mod 3) times."""
    ones = twos = 0
    for v in nums:
        ones = (ones ^ v) & ~twos
        twos = (twos ^ v) & ~ones
    return ones


def single_number_bitcount(nums):
    """Per-bit counting mod 3 over 32 bits, then convert back from two's complement."""
    out = 0
    for b in range(32):
        if sum((v >> b) & 1 for v in nums) % 3:
            out |= 1 << b
    return out - (1 << 32) if out >= 1 << 31 else out


def brute(nums):
    return next(v for v, c in Counter(nums).items() if c == 1)


if __name__ == "__main__":
    assert single_number_thrice([2, 2, 3, 2]) == 3
    assert single_number_thrice([0, 1, 0, 1, 0, 1, 99]) == 99
    assert single_number_thrice([-2, -2, 1, 1, 4, 1, 4, 4, -5, -2]) == -5   # negatives work too
    rng = random.Random(98)
    for _ in range(1000):
        vals = rng.sample(range(-1000, 1000), rng.randint(1, 8))
        nums = [vals[0]] + [v for v in vals[1:] for _ in range(3)]
        rng.shuffle(nums)
        assert single_number_thrice(nums) == single_number_bitcount(nums) == brute(nums)
    print("all tests passed")

Two-word state machine and per-bit counting mod 3, cross-checked against a Counter on random inputs that include negatives.

Complexity

Time: O(n). Space: O(1). Per-bit counting is O(32n) and needs a 32-bit sign correction in Python.

By level

Fresher: Explains why XOR fails and counts each bit position modulo 3 to rebuild the answer. Handles the sign for negative values.

Mid: Implements the ones and twos state machine and explains the transitions per bit. Generalizes the counting idea to k repetitions.

Senior: Derives state machine formulas from truth tables, and discusses readability trade-offs of compact bit tricks versus per-bit counting in shared code. Documents the invariant next to the code so reviewers can verify it.

Key points

  • XOR fails when copies come in threes
  • Each bit's count mod 3 gives the single's bit
  • ones and twos encode the count per bit
  • All 32 positions update together
  • Works for negatives

Common mistakes

  • Trying plain XOR
  • Forgetting the sign fix in the per-bit version
  • Swapping the update order of ones and twos
  • Using a hash map when O(1) space is required

Follow-ups

  • Generalize to every other value appearing k times
  • How do you find two values that each appear once while others appear twice?
  • How would you derive the update formulas from a truth table?

Tips

  • Start with the per-bit counting idea
  • Then show the state machine as an optimization
  • Test a negative single value

Evaluation rubric

  • Correct per-bit idea
  • Correct state machine or counting
  • Handles negatives
  • O(1) space
99.algorithms-0099Hardsenior

Bitmask DP for the travelling salesman problem: find the cheapest tour that visits every city exactly once and returns to the start, for up to about 16 cities.

Let dp[mask][j] be the cheapest path that starts at city 0, visits exactly the cities in mask, and ends at j. Extend each state by a city k not in mask: dp[mask | 1 << k][k] = min(dp[mask][j] + dist[j][k]). The answer adds the return edge from each end city. Held-Karp runs in O(2^n * n^2) time and O(2^n * n) space, compared with O(n!) for trying every order.

Full answer

Problem

Given an n x n matrix dist of travel costs (not necessarily symmetric), return the minimum cost of a tour that starts at city 0, visits every city exactly once and returns to city 0.

Example: [[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]] has a best tour of 80 (0, 1, 3, 2, 0).

Constraints: 1 <= n <= 16, costs from 1 to 1,000.

Brute force

Try all (n - 1)! orders of the other cities and sum each route: O(n!), about 1.3 * 10^12 for n = 16.

Optimal approach

Held-Karp:

  1. dp[1][0] = 0 (only city 0 visited, standing at 0); everything else infinity.
  2. For every mask containing city 0, every end j in mask with a finite value, and every k not in mask: relax dp[mask | 1 << k][k] with dp[mask][j] + dist[j][k].
  3. Answer: min(dp[full][j] + dist[j][0]) for j from 1 to n - 1.

Masks are processed in increasing numeric order, which guarantees that every subset is finished before any of its supersets (adding a bit always increases the number).

Why it works

The best way to finish a tour only depends on which cities are already visited and where you are now, not on the order they were visited in. So all partial paths with the same (mask, end) can be merged into one state that keeps the cheapest cost. There are 2^n * n such states, each extended in n ways. The cross-check against full permutation search confirms the result, including asymmetric costs.

Complexity

O(2^n * n^2) time and O(2^n * n) space. For n = 16 that is about 16.8 million transitions, which is fine in compiled languages and a few seconds in Python.

Code

python
import random
from itertools import permutations


def tsp(dist):
    """Shortest tour visiting every city once and returning to city 0 (Held-Karp).
    dp[mask][j] = cheapest path from 0 covering `mask` and ending at j. O(2^n * n^2) time, O(2^n * n) space."""
    n = len(dist)
    if n == 1:
        return 0
    INF = float("inf")
    full = 1 << n
    dp = [[INF] * n for _ in range(full)]
    dp[1][0] = 0
    for mask in range(full):
        if not mask & 1:
            continue                     # every path starts at city 0
        for j in range(n):
            cur = dp[mask][j]
            if cur == INF:
                continue
            for k in range(n):
                if mask >> k & 1:
                    continue
                nm = mask | 1 << k
                if cur + dist[j][k] < dp[nm][k]:
                    dp[nm][k] = cur + dist[j][k]
    return min(dp[full - 1][j] + dist[j][0] for j in range(1, n))


def brute(dist):
    n = len(dist)
    if n == 1:
        return 0
    best = float("inf")
    for p in permutations(range(1, n)):
        route = (0,) + p + (0,)
        best = min(best, sum(dist[a][b] for a, b in zip(route, route[1:])))
    return best


if __name__ == "__main__":
    d = [[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]
    assert tsp(d) == 80                                 # 0-1-3-2-0
    assert tsp([[0]]) == 0 and tsp([[0, 3], [4, 0]]) == 7
    rng = random.Random(99)
    for _ in range(150):
        n = rng.randint(1, 7)
        m = [[0 if i == j else rng.randint(1, 20) for j in range(n)] for i in range(n)]   # asymmetric is fine
        assert tsp(m) == brute(m)
    print("all tests passed")

Save as b99_bitmask_dp_tsp.py and run python3 b99_bitmask_dp_tsp.py. It prints all tests passed (Python 3.13.5).

Edge cases

n = 1 (cost 0). n = 2 (there and back). Asymmetric costs (handled; the direction matters). Missing edges (use infinity and check the answer). n above about 20 (memory and time grow too fast; use heuristics or branch and bound).

Pattern

DP over subsets with a bitmask state. The same structure solves the shortest path visiting all nodes (BFS over (mask, node)), assignment problems with n <= 20, minimum cost to connect groups, and partitioning into k equal-sum subsets.

python
import random
from itertools import permutations


def tsp(dist):
    """Shortest tour visiting every city once and returning to city 0 (Held-Karp).
    dp[mask][j] = cheapest path from 0 covering `mask` and ending at j. O(2^n * n^2) time, O(2^n * n) space."""
    n = len(dist)
    if n == 1:
        return 0
    INF = float("inf")
    full = 1 << n
    dp = [[INF] * n for _ in range(full)]
    dp[1][0] = 0
    for mask in range(full):
        if not mask & 1:
            continue                     # every path starts at city 0
        for j in range(n):
            cur = dp[mask][j]
            if cur == INF:
                continue
            for k in range(n):
                if mask >> k & 1:
                    continue
                nm = mask | 1 << k
                if cur + dist[j][k] < dp[nm][k]:
                    dp[nm][k] = cur + dist[j][k]
    return min(dp[full - 1][j] + dist[j][0] for j in range(1, n))


def brute(dist):
    n = len(dist)
    if n == 1:
        return 0
    best = float("inf")
    for p in permutations(range(1, n)):
        route = (0,) + p + (0,)
        best = min(best, sum(dist[a][b] for a, b in zip(route, route[1:])))
    return best


if __name__ == "__main__":
    d = [[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]
    assert tsp(d) == 80                                 # 0-1-3-2-0
    assert tsp([[0]]) == 0 and tsp([[0, 3], [4, 0]]) == 7
    rng = random.Random(99)
    for _ in range(150):
        n = rng.randint(1, 7)
        m = [[0 if i == j else rng.randint(1, 20) for j in range(n)] for i in range(n)]   # asymmetric is fine
        assert tsp(m) == brute(m)
    print("all tests passed")

Held-Karp with masks in increasing order, cross-checked against all permutations on random asymmetric matrices up to 7 cities.

Complexity

Time: O(2^n * n^2). Space: O(2^n * n). Exact TSP is NP-hard; this is the classic exponential but far better than O(n!) method.

By level

Fresher: Explains why trying all orders is too slow and describes the (mask, city) state with a small example. Follows the transitions with guidance.

Mid: Implements Held-Karp correctly, reconstructs the tour with parent pointers, and states the complexity. Applies masks to the visit-all-nodes BFS variant.

Senior: Discusses heuristics such as nearest neighbour with 2-opt, branch and bound, and solver tools for large instances. Estimates memory before choosing bitmask DP and explains where exact methods stop being practical.

Key points

  • State = (visited mask, current city)
  • Order inside the mask does not matter for the future
  • Increasing mask order processes subsets first
  • Add the return edge at the end
  • O(2^n * n^2)

Common mistakes

  • Using a mask without the start city bit
  • Forgetting the return to city 0
  • Iterating masks in an order where supersets come before subsets
  • Trying this for n = 30

Follow-ups

  • How would you rebuild the actual tour?
  • How do you find the shortest path that visits all nodes without returning?
  • What heuristics would you use for 1,000 cities?

Tips

  • Explain why the order inside the mask does not matter
  • Estimate the number of states before coding
  • Mention practical limits on n

Evaluation rubric

  • Correct state and transition
  • Correct answer with the return edge
  • Correct complexity
  • Knows the limits
100.algorithms-0100Easyfresher

Hamming distance and reversing bits: count the bit positions where two integers differ, sum that over all pairs efficiently, and reverse the bits of a 32-bit unsigned integer.

The Hamming distance of a and b is the popcount of a XOR b. Summing over all pairs one pair at a time is O(n^2), but per bit position the number of differing pairs is ones times zeros, which gives O(32n). Reversing bits shifts the result left and moves in x's lowest bit 32 times.

Full answer

Problem

  1. Return the number of positions where the bits of a and b differ.
  2. Return the sum of Hamming distances over all pairs in nums.
  3. Reverse the bits of a 32-bit unsigned integer.

Example: hamming(1, 4) = 2 (001 versus 100). For [4, 14, 2] the total is 6 (2 + 2 + 2). Reversing 00000010100101000001111010011100 gives 00111001011110000010100101000000, which is 964176192.

Constraints: values are 32-bit unsigned (0 to 2^32 - 1); up to 10^4 numbers for the total.

Brute force

Compare bit strings character by character for each pair: O(32) per pair and O(32 n^2) for all pairs. Reversing by converting to a padded 32-character string and reversing it works but allocates strings.

Optimal approach

  • Hamming distance: x = a ^ b, then count set bits with x &= x - 1.
  • Total over pairs: for each bit b in 0..31, let ones be how many numbers have bit b set; add ones * (n - ones).
  • Reverse bits: out = 0; repeat 32 times: out = (out << 1) | (x & 1), x >>= 1.

Why it works

XOR leaves a 1 exactly where the two inputs differ, so its popcount is the distance. For the total, each bit position contributes independently: a pair differs at bit b exactly when one number has a 1 there and the other a 0, and there are ones * zeros such pairs. Reversal moves the lowest bit of x into the result and shifts earlier bits up, so after 32 steps bit i has moved to position 31 - i.

Complexity

Hamming distance: O(number of set bits). Total: O(32n) time, O(1) space. Reverse bits: O(32). For many reverse calls, a 256-entry lookup table reverses a byte at a time.

Code

python
import random


def hamming_distance(a, b):
    """Number of bit positions that differ: popcount of a XOR b."""
    x, n = a ^ b, 0
    while x:
        x &= x - 1
        n += 1
    return n


def total_hamming(nums):
    """Sum over all pairs in O(32 * n): at each bit, ones * zeros pairs differ."""
    total, n = 0, len(nums)
    for b in range(32):
        ones = sum((v >> b) & 1 for v in nums)
        total += ones * (n - ones)
    return total


def reverse_bits(x):
    """Reverse a 32-bit unsigned integer."""
    out = 0
    for _ in range(32):
        out = (out << 1) | (x & 1)
        x >>= 1
    return out


def brute_total(nums):
    return sum(hamming_distance(nums[i], nums[j]) for i in range(len(nums)) for j in range(i + 1, len(nums)))


if __name__ == "__main__":
    assert hamming_distance(1, 4) == 2 and hamming_distance(3, 1) == 1 and hamming_distance(7, 7) == 0
    assert total_hamming([4, 14, 2]) == 6
    assert reverse_bits(0b00000010100101000001111010011100) == 964176192
    assert reverse_bits(1) == 1 << 31 and reverse_bits(0) == 0
    rng = random.Random(100)
    for _ in range(500):
        nums = [rng.randint(0, (1 << 32) - 1) for _ in range(rng.randint(0, 12))]
        assert total_hamming(nums) == brute_total(nums)
        v = rng.randint(0, (1 << 32) - 1)
        assert reverse_bits(v) == int(format(v, "032b")[::-1], 2)
        assert reverse_bits(reverse_bits(v)) == v
    print("all tests passed")

Save as b100_hamming_reverse_bits.py and run python3 b100_hamming_reverse_bits.py. It prints all tests passed (Python 3.13.5).

Edge cases

Equal numbers (distance 0). Zero and the maximum 32-bit value. Reversal of 1 is 1 << 31. Fewer than two numbers (total 0). In fixed-width languages, use unsigned shifts (>>> in Java) so the sign bit is not copied.

Pattern

XOR to find differences, and per-bit counting to turn an O(n^2) pair sum into O(32n). Related: sum of XOR over all pairs, maximum XOR pair (binary trie), and error-detecting codes that rely on Hamming distance.

python
import random


def hamming_distance(a, b):
    """Number of bit positions that differ: popcount of a XOR b."""
    x, n = a ^ b, 0
    while x:
        x &= x - 1
        n += 1
    return n


def total_hamming(nums):
    """Sum over all pairs in O(32 * n): at each bit, ones * zeros pairs differ."""
    total, n = 0, len(nums)
    for b in range(32):
        ones = sum((v >> b) & 1 for v in nums)
        total += ones * (n - ones)
    return total


def reverse_bits(x):
    """Reverse a 32-bit unsigned integer."""
    out = 0
    for _ in range(32):
        out = (out << 1) | (x & 1)
        x >>= 1
    return out


def brute_total(nums):
    return sum(hamming_distance(nums[i], nums[j]) for i in range(len(nums)) for j in range(i + 1, len(nums)))


if __name__ == "__main__":
    assert hamming_distance(1, 4) == 2 and hamming_distance(3, 1) == 1 and hamming_distance(7, 7) == 0
    assert total_hamming([4, 14, 2]) == 6
    assert reverse_bits(0b00000010100101000001111010011100) == 964176192
    assert reverse_bits(1) == 1 << 31 and reverse_bits(0) == 0
    rng = random.Random(100)
    for _ in range(500):
        nums = [rng.randint(0, (1 << 32) - 1) for _ in range(rng.randint(0, 12))]
        assert total_hamming(nums) == brute_total(nums)
        v = rng.randint(0, (1 << 32) - 1)
        assert reverse_bits(v) == int(format(v, "032b")[::-1], 2)
        assert reverse_bits(reverse_bits(v)) == v
    print("all tests passed")

Kernighan popcount over XOR, per-bit total over pairs, and 32-step reversal, cross-checked against pairwise sums and string reversal.

Complexity

Time: O(32n) for the pair total; O(32) for reversal. Space: O(1). A byte lookup table reduces reversal to 4 lookups.

By level

Fresher: Computes the distance with XOR and a bit count, and reverses bits with a loop of 32 shifts. Traces both on small values.

Mid: Turns the pair sum into per-bit counts and explains why bit positions are independent. Handles unsigned behaviour across languages.

Senior: Discusses lookup tables and hardware instructions for bit reversal and popcount, and uses of Hamming distance in error-correcting codes and similarity hashing. Explains how SimHash fingerprints use it to find near-duplicate documents.

Key points

  • Distance = popcount(a XOR b)
  • Per bit, differing pairs = ones * zeros
  • Pair total in O(32n)
  • Reverse by shifting in the lowest bit 32 times
  • Use unsigned shifts in fixed-width languages

Common mistakes

  • Summing pairs directly in O(n^2)
  • Reversing only the significant bits instead of all 32
  • Using signed shifts in Java or C
  • Forgetting that Python integers are unbounded when emulating 32-bit values

Follow-ups

  • How would you speed up reversal for millions of calls?
  • How do you find the pair with the maximum XOR?
  • Where is Hamming distance used in practice?

Tips

  • Show XOR on two small numbers
  • Explain the ones * zeros count
  • Mention lookup tables for repeated reversal

Evaluation rubric

  • Correct distance
  • O(32n) pair total
  • Correct 32-bit reversal
  • Edge cases