Remove Boxes solution explained

Remove Boxes needs a three-index DP: best(l, r, extra) is the top score for boxes l through r when extra boxes of the same color as box l are already waiting to be removed with it. Either remove box l and its extras now for (extra + 1)² points, or clear the stretch up to a later box m of the same color and carry the group forward. Memoized, that is O(n⁴) time and O(n³) memory.

By Published 9 min read

The game in plain words

You have a row of boxes, each painted a color, written as a list of numbers. On each move you choose a block of neighboring boxes that all share one color, remove the whole block, and score the square of its length. The boxes on either side then close the gap and become neighbors. Keep going until the row is empty. Return the largest total score you can reach.

The square is what makes it hard. Three separate single boxes of one color score 3 points, but the same three removed together score 9. So you often want to remove the boxes that sit between equal colors first, purely to bring those colors together.

Sample rows made up for this page
BoxesBest scoreA plan that gets there
[7, 8, 9]3No two colors match, so three single removals
[4, 4, 4]9One block of three
[1, 2, 1, 2, 1]11Take each 2 alone (1 + 1), then the three 1s together (9)
[3, 1, 3, 3, 2, 3]18Remove the 1 and the 2 first, then four 3s for 16
[3, 3, 1, 3, 1, 2]12Remove the first 1, then three 3s (9), then the other 1 and the 2
Sample rows made up for this page. Scroll sideways on a small screen.

Ask how many boxes there can be and how many colors. The memoized solution stores about n³ values, which is fine for a row of around a hundred boxes and not for many thousands.

Why it is on hard interview lists

This is one of the classic examples where the natural state is too small. Candidates who know interval DP write best(l, r), get stuck, and the interviewer watches whether they can explain exactly what information is missing and add it. That skill, extending a state until the subproblems become independent, carries over to many other problems.

Why two indexes are not enough

Try defining best(l, r) as the top score for boxes l through r alone. Look at [3, 1, 3, 3, 2, 3]. The best play removes the 1 and the 2 and then takes all four 3s for 16 points. Any split of the range into a left part and a right part scores those 3s separately, and a square of a sum beats the sum of squares. The score of a range depends on how many boxes from outside it will end up joining its boxes. So the state needs to carry that count.

Define best(l, r, extra) as the best score for boxes l to r, given that extra boxes with the same color as box l sit just to its left and will be removed together with it. Now there are two choices for box l:

  • Remove it now with its extras. Score (extra + 1)², plus best(l + 1, r, 0) for the rest.
  • Delay it to join a later box m of the same color. First clear everything strictly between, best(l + 1, m - 1, 0). Then box l and its extras sit next to box m, so the rest is best(m, r, extra + 1).

A small speed-up: if box l + 1 already has the same color as box l, slide l forward and add one to extra before choosing. Consecutive equal boxes always leave together in an optimal play, so there is no reason to branch on them.

Slow approach: try every move in every order

The honest brute force simulates the game. At each step, list every maximal block of one color, remove it, score it, and recurse on the shorter row. The number of move orders is exponential, so it only works as a test oracle on short rows.

def boxes_slow(row):
    if not row:
        return 0
    top = 0
    i = 0
    while i < len(row):
        j = i
        while j + 1 < len(row) and row[j + 1] == row[i]:
            j += 1
        size = j - i + 1
        top = max(top, size * size + boxes_slow(row[:i] + row[j + 1:]))
        i = j + 1
    return top
Exhaustive search over removal orders; exponential.

Main approach: memoized three-index recursion

The recursion on (l, r, extra) has at most n³ distinct states, and each one loops over up to n choices of m. Top-down memoization is the natural way to write it, because many states are never reached and the loop order for a bottom-up table is awkward to get right under pressure.

from functools import lru_cache

def remove_boxes(boxes):
    b = tuple(boxes)

    @lru_cache(maxsize=None)
    def best(l, r, extra):
        # extra = boxes colored like b[l] already glued on its left
        if l > r:
            return 0
        while l < r and b[l + 1] == b[l]:
            l += 1
            extra += 1
        score = (extra + 1) ** 2 + best(l + 1, r, 0)
        for m in range(l + 2, r + 1):
            if b[m] == b[l]:
                score = max(score, best(l + 1, m - 1, 0) + best(m, r, extra + 1))
        return score

    return best(0, len(b) - 1, 0)
Python: O(n⁴) time and O(n³) memory in the worst case.
function removeBoxes(boxes) {
  const n = boxes.length;
  const memo = new Map();
  function best(l, r, extra) {
    if (l > r) return 0;
    while (l < r && boxes[l + 1] === boxes[l]) {
      l++;
      extra++;
    }
    const key = (l * n + r) * n + extra;
    if (memo.has(key)) return memo.get(key);
    let score = (extra + 1) * (extra + 1) + best(l + 1, r, 0);
    for (let m = l + 2; m <= r; m++) {
      if (boxes[m] === boxes[l]) {
        score = Math.max(score, best(l + 1, m - 1, 0) + best(m, r, extra + 1));
      }
    }
    memo.set(key, score);
    return score;
  }
  return best(0, n - 1, 0);
}
JavaScript: a Map keyed by one number built from (l, r, extra).

Follow [1, 2, 1, 2, 1] from the top. Removing the first 1 at once gives 1 + best([2, 1, 2, 1]). Delaying it to the middle 1 clears the first 2 (1 point) and continues with best([1, 2, 1], extra 1). There, delaying again clears the second 2 (1 point) and reaches the last 1 with extra 2, which scores 3² = 9. Total: 1 + 1 + 9 = 11.

Complexity

Work and memory for n boxes
ApproachTimeMemoryUse
Simulate every removal orderExponentialO(n²) for the row copies on the stackTest oracle for rows of up to about eight boxes
Memoized best(l, r, extra)O(n⁴) worst caseO(n³)The solution to present
Work and memory for n boxes. Scroll sideways on a small screen.

The bound is loose in practice. The inner loop only runs over boxes that match box l, and the slide over equal neighbors removes many states, so rows with many colors finish far faster than n⁴ suggests.

Edge cases

  • An empty row scores 0; make sure the first call with r = -1 returns immediately.
  • All boxes one color: one move worth n².
  • All colors different: n single removals worth n points in total.
  • Alternating colors like [1, 2, 1, 2, 1]: every choice of which color to sacrifice matters, which makes it a strong test.
  • Deep recursion: rows near the upper size limit can recurse about n levels deep, which is fine for Python's default limit of 1000 but worth checking.

Pitfalls

  • Removing the biggest block first. On [3, 3, 1, 3, 1, 2] that greedy rule takes the leading pair of 3s, after which no order of moves gets past 10 points, while the best play scores 12.
  • Stopping at best(l, r). It cannot see boxes outside the range that will join, so it undercounts. Explain why before adding the third index.
  • Forgetting to reset extra to 0 for the middle segment. The boxes between l and m are removed on their own, with nothing glued on.
  • Memo keys that collide. In JavaScript, a key like l + r + extra maps different states together. Build a positional key, or use a nested array.
  • Writing the bottom-up table without a clear order. best(m, r, extra + 1) has a larger extra but a shorter range, so ordering by range length works. If unsure, stay top-down.

Talking through it

Fictional example

A candidate explaining why the state needs three numbers
Candidate
If I only track l and r, I lose the fact that matching boxes outside the range may be removed with box l. In 3-1-3-3-2-3 all four 3s can leave together, and no left-right split can see that.
Candidate
So I add extra: how many boxes with box l's color are already waiting on its left. Then I either remove box l with them now, or clear the gap up to a later match m and pass extra plus one to the call that starts at m.
Candidate
There are n cubed states and each loops over n matches, so quartic in the worst case, much less in practice. I'll check it on 1-2-1-2-1, which should give 11.

Strange Printer is the gentler cousin: it also merges equal items across a gap, but needs only two indexes because a shared stroke costs nothing extra. Best Time to Buy and Sell Stock with Transaction Fee shows the other end of the DP range, with two states per day and constant memory. For the data-structure side of revision, see data structure interview questions.

Working on it with Natively

Remove Boxes is the kind of problem where seeing a second explanation helps. In practice, Natively can read the problem from a screenshot and suggest a state and code in its overlay, which you can hold up against your own reasoning about the extra index. Because it can also transcribe a mock round on your computer, you can review afterwards whether you justified the third index before writing it. Read about an AI interview assistant on Mac and Windows.

Questions people ask

How do you solve Remove Boxes?

Use memoized recursion on best(l, r, extra), where extra counts boxes with box l's color already waiting to be removed with it. Either remove box l now for (extra + 1)² plus best(l + 1, r, 0), or clear the gap to a later matching box m and continue with best(m, r, extra + 1).

Why does Remove Boxes need three dimensions?

The score of a range depends on how many same-colored boxes from outside it will be removed together with its boxes. Two indexes cannot record that, so the third index carries the count.

What is the time complexity of Remove Boxes?

O(n⁴) time and O(n³) memory in the worst case: about n³ states, each scanning up to n matching boxes. Real inputs usually touch far fewer states.

Does a greedy strategy work for Remove Boxes?

No. Removing the largest block first fails on [3, 3, 1, 3, 1, 2]: after taking the two leading 3s the best you can reach is 10, while removing a 1 first leads to 12.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP