Skip to main content

354 - Russian Doll Envelopes

Difficulty: Hard | Pattern: Sorting + LIS (Binary Search) | Company tags: Amazon, Google, Facebook

Problem Statement

You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and height of an envelope.

One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.

Return the maximum number of envelopes you can Russian doll (put one inside the other).

Note: You cannot rotate an envelope.

Example:

Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
Output: 3 ([2,3] → [5,4] → [6,7])

Approach: Sort + LIS — O(n log n)

Key insight:

  1. Sort by width ascending. For same width, sort by height descending (critical!).
  2. Apply LIS on heights only.

The descending height for same width prevents putting two same-width envelopes inside each other.

import bisect

def maxEnvelopes(envelopes: list[list[int]]) -> int:
# Sort by width asc, height desc for same width
envelopes.sort(key=lambda x: (x[0], -x[1]))

# LIS on heights (patience sorting)
tails = []
for _, h in envelopes:
pos = bisect.bisect_left(tails, h)
if pos == len(tails):
tails.append(h)
else:
tails[pos] = h

return len(tails)

Dry Run

envelopes = [[5,4],[6,4],[6,7],[2,3]]

After sort: [[2,3],[5,4],[6,7],[6,4]] (Note: [6,7] before [6,4] because heights sorted descending for same width)

LIS on heights [3,4,7,4]:

htailsaction
3[]append → [3]
4[3]4 gt all → [3,4]
7[3,4]7 gt all → [3,4,7]
4[3,4,7]bisect_left finds pos=1 → replace tails[1]=4 → [3,4,7]

Length = 3

Why Descending Height for Same Width?

With [6,4] and [6,7]: both have width 6, so neither can contain the other. Sorting [6,7],[6,4] means in LIS, 4 replaces 7 and can't extend the sequence — correctly preventing counting both.

Complexity

  • Time: O(n log n)
  • Space: O(n)