Russian Doll Envelopes solution explained

Russian Doll Envelopes asks for the most envelopes you can stack one inside another, where an envelope fits only if both its width and its height are strictly smaller. Sort by width ascending and, for equal widths, by height descending; then the answer is the longest strictly increasing run of heights, found with patience sorting and binary search in O(n log n). The descending tie-break is the part interviewers listen for.

By Published 8 min read

The problem, in plain terms

You have a pile of envelopes, each described by a width and a height. One envelope can go inside another only if it is strictly narrower and strictly shorter. You cannot rotate them. What is the largest number of envelopes you can nest into a single stack? Order in the input does not matter; you are free to pick any subset and arrange it.

Case A
  envelopes: (3,5) (6,4) (6,7) (2,2) (4,6) (7,8) (4,3)
  one best chain: (2,2) -> (3,5) -> (4,6) -> (6,7) -> (7,8)
  answer: 5

Case B (the tie trap)
  envelopes: (1,1) (2,2) (2,3)
  (2,2) and (2,3) have the same width, so they cannot nest
  answer: 2
Two cases, made up for this page

Ask whether equal sides count as fitting (here they do not), whether rotation is allowed (here it is not), and whether you return the count or the chain. These three answers change the solution, so they are worth thirty seconds at the start.

Why interviewers like it

It is longest increasing subsequence in disguise, with one extra trap. Candidates who know the one-dimensional problem often sort by width, run it on heights and pass the easy cases, then fail on Case B. The interviewer wants to hear you find that failure yourself and explain why sorting equal widths by descending height fixes it. It also tests whether you can move from an O(n²) DP to the binary search version without losing correctness.

First answer: sort, then an O(n²) DP

Sort by width. Now any valid chain appears in left-to-right order in the sorted list. Let chain[i] be the longest chain that ends with envelope i. It is 1 plus the best chain[j] over every earlier j whose width and height are both strictly smaller. Checking both dimensions here means ties in width are handled automatically, so the sort order of equal widths does not matter in this version.

def max_nesting_quadratic(envelopes):
    env = sorted(envelopes)
    chain = [1] * len(env)
    for i, (w, h) in enumerate(env):
        for j in range(i):
            if env[j][0] < w and env[j][1] < h and chain[j] + 1 > chain[i]:
                chain[i] = chain[j] + 1
    return max(chain, default=0)
Python: sort by width, quadratic DP over both dimensions

This is O(n²) time and O(n) memory. For a few thousand envelopes it is fine; for hundreds of thousands it is not, and that is usually the prompt for the faster idea.

Optimal: the tie-break, then patience sorting

If widths were all different, sorting by width would leave only one condition: heights must strictly increase along the chain. That is exactly longest increasing subsequence on the list of heights. The trouble is equal widths. With heights sorted ascending among them, (2,2) then (2,3) looks like an increase, and the run counts two envelopes that cannot nest. Sort equal widths by height descending instead. Inside a group of equal widths the heights now go down, so a strictly increasing run can take at most one envelope from each group, which is exactly the rule.

For the increasing run, keep a list tails where tails[k] is the smallest possible last height of an increasing run of length k + 1 seen so far. For each height, find the first entry that is greater than or equal to it (a lower bound) and replace it, or append if there is none. The list stays sorted, its length is the answer, and each step is one binary search. The lower bound, not the upper bound, is what makes the run strictly increasing: an equal height replaces an entry instead of extending past it.

from bisect import bisect_left


def max_nesting(envelopes):
    env = sorted(envelopes, key=lambda e: (e[0], -e[1]))
    tails = []  # tails[k] = smallest last height of an increasing run of length k + 1
    for _, h in env:
        k = bisect_left(tails, h)
        if k == len(tails):
            tails.append(h)
        else:
            tails[k] = h
    return len(tails)
Python: width ascending, height descending, then bisect. O(n log n).
#include <algorithm>
#include <utility>
#include <vector>

int maxNesting(std::vector<std::pair<int, int>> env) {
    std::sort(env.begin(), env.end(), [](const auto& x, const auto& y) {
        if (x.first != y.first) return x.first < y.first;
        return x.second > y.second;  // equal widths: taller first
    });
    std::vector<int> tails;
    for (const auto& e : env) {
        auto it = std::lower_bound(tails.begin(), tails.end(), e.second);
        if (it == tails.end()) tails.push_back(e.second);
        else *it = e.second;
    }
    return static_cast<int>(tails.size());
}
C++17: the same idea with std::sort and std::lower_bound

Trace Case A. After sorting: (2,2) (3,5) (4,6) (4,3) (6,7) (6,4) (7,8). Heights: 2, 5, 6, 3, 7, 4, 8. Tails grows to [2, 5, 6], then 3 replaces 5 to give [2, 3, 6], 7 appends to give [2, 3, 6, 7], 4 replaces 6, and 8 appends. Final length 5. Note that tails is not itself a valid chain at the end; only its length is meaningful.

Complexity summary

n envelopes
ApproachTimeExtra memoryNote
Every subsetO(2^n × n)O(n)Only for testing
Sort plus quadratic DPO(n²)O(n)Handles ties without a special sort
Tie-break sort plus binary searchO(n log n)O(n)Expected answer
n envelopes. Scroll sideways on a small screen.

Edge cases to try

  • No envelopes: return 0.
  • One envelope: return 1.
  • Every envelope the same size: return 1, since none fits strictly inside another.
  • All envelopes share one width but have different heights: still 1. This is the case that breaks the ascending tie-break.
  • Heights equal but widths different: still 1, which checks the strict lower bound.
  • Envelopes already in nesting order, and in reverse order: the sort should make both behave the same.

Mistakes to avoid

  • Sorting equal widths by ascending height, which lets two same-width envelopes into one chain.
  • Using an upper bound (bisect_right) on heights, which allows equal heights to extend the run.
  • Reading the tails list as the answer chain. To recover the chain, store a parent index for each envelope as you go.
  • Sorting by area or by the sum of sides and then running the one-dimensional trick on heights. Those orders do keep any chain in order, but neither fixes the width, so the pairwise check of the quadratic DP is still needed.
  • Allowing rotation when the problem did not say so, or the reverse.

Follow-ups

  • Return the chain itself. Keep, for each tails position, the index of the envelope stored there, and for each envelope the index of the one before it. Walk the parents back from the last tail.
  • Rotation is allowed. Normalize each envelope so width is the smaller side before sorting, then solve as usual.
  • Three dimensions, like boxes. Sorting fixes only one dimension, so the remaining two need the quadratic DP or a more advanced structure; say so rather than forcing the 2D trick.
  • Non-strict fit. If equal sides are allowed, sort equal widths ascending and use an upper bound instead.

How to explain it out loud

Fictional example

Finding the tie bug before the interviewer does
Candidate
If I sort by width, any chain shows up left to right, so I only need heights to increase. That is longest increasing subsequence.
Candidate
Wait, two envelopes with the same width would both count if their heights went up. Those cannot nest.
Candidate
So for equal widths I sort heights from tallest to shortest. Then an increasing run can never take two from the same width.
Interviewer
And the increasing run itself?
Candidate
Patience sorting: a sorted list of the smallest tail for each length, updated with a lower-bound binary search. That keeps it strict and makes the whole thing O(n log n).

Number of Longest Increasing Subsequence asks how many longest runs exist, not just their length. Largest Divisible Subset is another sort-then-chain problem where the order after sorting is what makes the DP work. Wiggle Subsequence changes the rule from increasing to alternating. The plain longest increasing subsequence problem is the warm-up to mention first.

Practicing it with Natively

Russian Doll Envelopes is a good drill for catching your own bug out loud, because the wrong tie-break passes most simple examples. Natively, a desktop app for Mac and Windows, can read the problem from a screenshot during practice and talk through the sort order, and the transcript of your mock answer shows whether you mentioned the equal-width case unprompted. More on the AI interview assistant page.

Questions people ask

How do you solve Russian Doll Envelopes?

Sort envelopes by width ascending and, for equal widths, by height descending. Then find the longest strictly increasing subsequence of the heights with patience sorting and a lower-bound binary search. Its length is the answer.

Why sort equal widths by descending height?

Envelopes with the same width cannot nest. With their heights in descending order, a strictly increasing run can pick at most one of them, so the one-dimensional search respects the two-dimensional rule.

What is the time complexity of Russian Doll Envelopes?

O(n log n): the sort plus one binary search per envelope, with O(n) extra memory. A simpler DP that checks every earlier envelope is O(n²).

Is Russian Doll Envelopes the same as longest increasing subsequence?

It reduces to it after sorting by width. The extra step is the descending tie-break for equal widths, which stops two same-width envelopes from both joining the chain.

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