Skip to main content
Back to problems
#354
Hard Algorithms

Russian doll envelopes

Array Binary Search Dynamic Programming Sorting
37.7% acceptance
Jan 12, 2026
6449
170
You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the 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 (i.e., put one inside the other). Note: You cannot rotate an envelope.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn max_envelopes(envelopes: Vec<Vec<i32>>) -> i32 {
    let mut envelopes = envelopes;
    // Sort by width ascending, then by height descending
    envelopes.sort_by(|a, b| {
      if a[0] == b[0] {
        b[1].cmp(&a[1])
      } else {
        a[0].cmp(&b[0])
      }
    });
    
    // Find LIS on heights
    let mut dp = Vec::new();
    for env in envelopes {
      let height = env[1];
      match dp.binary_search(&height) {
        Ok(_) => {},
        Err(pos) => {
          if pos == dp.len() {
            dp.push(height);
          } else {
            dp[pos] = height;
          }
        }
      }
    }
    
    dp.len() as i32
  }
}