Skip to content
Preptima
hardCodingMidSeniorStaff

Envelopes nest only when both width and height are strictly larger. How many can you nest, and why must equal widths be sorted by height descending?

Russian doll envelopes reduce to a longest increasing subsequence. Sort by width ascending, break width ties by height descending, then run the O(n log n) tails search on heights. The descending tie-break stops equal widths from chaining, since a strictly increasing run then takes at most one per width.

4 min readUpdated 2026-10-10

Answer

Short answer

Russian doll envelopes are a longest increasing subsequence in disguise. Sort the envelopes by width ascending and, when widths are equal, by height descending. Then the answer is the longest strictly increasing subsequence of the heights, found in O(n log n) with the tails array. The descending tie-break is what stops two envelopes of the same width from being counted as nested.

Was this answer helpful?

Likely follow-ups

  • Envelopes may nest when width and height are greater than or equal. Which two lines change?
  • Widths must strictly increase but equal heights are allowed. Does any tie-break order still work?
  • Boxes have length, width and height and may not be rotated. What is your approach now?
  • Return the envelopes in nesting order, from the smallest outwards.

Related questions