2Brute2Best
🔥0
03

2D / envelopes (DP — Longest Increasing Subsequence Sub-pattern)

Items with two (or three) dimensions. Sort by one dimension so the order is fixed, then LIS on the other.

Signals in the problem statement
  • ›

    "envelopes", "boxes", "dolls" fitting inside each other

  • ›

    "bridges must not cross"

  • ›

    "team with no conflicts" (age and score)

What makes it different

The tie-break in the sort decides correctness: strict in both dimensions → equal first dimension sorted descending by the second. Boxes that can rotate become 3 items each.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Building Bridges
    Basic Anchor·GeeksforGeeks
    Medium
  2. 2
    Best Team With No Conflicts
    Slight Variation·LeetCode #1626
    Medium
  3. 3
    Box Stacking
    Medium·GeeksforGeeks
    Hard
  4. 4
    Russian Doll Envelopes
    Tricky / Edge Case·LeetCode #354
    Hard

Template

envelope-template.cpp
// 2-D chain, strictly bigger in both dimensions (Russian Doll Envelopes).
// Sort width ascending, and height DESCENDING for equal widths, then strict LIS on heights:
// two envelopes of the same width can never both be in one increasing run.
int maxNested(vector<vector<int>> env) {
    sort(env.begin(), env.end(), [](const vector<int>& x, const vector<int>& y) {
        return x[0] != y[0] ? x[0] < y[0] : x[1] > y[1];
    });
    vector<int> tails;
    for (auto& e : env) {
        auto it = lower_bound(tails.begin(), tails.end(), e[1]);
        if (it == tails.end()) tails.push_back(e[1]);
        else *it = e[1];
    }
    return tails.size();
}
Remember this · DP — Longest Increasing Subsequence
Trigger
Longest chain where each item must be bigger/fit inside the previous one (numbers, pairs, envelopes, words).
Think
Does each element extend the best chain ending at some smaller earlier element?
Key question
Sort first? Then what does "increasing" mean for these items?