Programming & Development / April 10, 2025

LeetCode 354: Russian Doll Envelopes – Patience Sorting & Longest Increasing Subsequence

LeetCode 354 Russian Doll Envelopes envelope nesting problem longest increasing subsequence LIS binary search dynamic programming sorting technique patience sorting python envelope problem

πŸ“˜ Problem Statement

You are given a list of envelopes with dimensions [width, height]. One envelope can fit into another if both the width and height of one are strictly smaller than the other.

πŸ”§ Goal: Return the maximum number of envelopes you can nest (Russian doll style).

πŸ“₯ Example

python

Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The sequence [[2,3] => [5,4] => [6,7]] can be nested.

🧠 Approach

This is a 2D version of Longest Increasing Subsequence (LIS).

πŸ’‘ Key Insight:

  1. Sort the envelopes:
  • Ascending by width
  • If widths are equal, descending by height
  1. Extract heights and run LIS on them.

Why sort heights in descending order when widths are equal?

To prevent envelopes with the same width from being nested.

🐍 Python Code (Using Binary Search for LIS)

python

from bisect import bisect_left

class Solution:
    def maxEnvelopes(self, envelopes: list[list[int]]) -> int:
        # Step 1: Sort by width ASC, height DESC
        envelopes.sort(key=lambda x: (x[0], -x[1]))

        # Step 2: Extract the heights
        heights = [h for w, h in envelopes]

        # Step 3: Apply LIS on heights
        lis = []

        for h in heights:
            idx = bisect_left(lis, h)
            if idx == len(lis):
                lis.append(h)
            else:
                lis[idx] = h

        return len(lis)

πŸ” Step-by-Step Breakdown

  1. Sort envelopes: [(2,3), (5,4), (6,7), (6,4)] β†’ sorted as [(2,3), (5,4), (6,7), (6,4)]
  • Note that (6,7) comes before (6,4) due to descending height for same width.
  1. Extract heights: [3, 4, 7, 4]
  2. Apply LIS:
  • 3 β†’ [3]
  • 4 β†’ [3, 4]
  • 7 β†’ [3, 4, 7]
  • 4 β†’ replaces index 1 (4), remains [3, 4, 7]

βœ… Final length = 3

⏱️ Time & Space Complexity

OperationComplexitySortingO(n log n)LIS (Binary Search)O(n log n)SpaceO(n)

🧡 Alternate Approach (DP – Slower)

You can use classic DP with O(nΒ²) time, but it's inefficient for large inputs.

🧭 Final Thoughts

This problem elegantly combines:

  • Sorting tricks
  • Dynamic programming (LIS)
  • Binary search (via bisect_left)

It’s an excellent real-world example of combining multiple algorithmic concepts. A must-practice for interview prep!


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex