Sub topic 9
Applications: Nesting Envelopes and Minimum Deletions
This chapter assumes you already know the O(n log n) tails-array algorithm from the earlier chapters. You should also know how bisect_left and bisect_right choose between strict and non-decreasing subsequences, and how parent pointers rebuild an actual subsequence. Here you will use that algorithm to solve problems that do not mention increasing subsequences at all.
Most LIS applications follow a two-step pattern:
- Turn the input into one sequence, often by sorting on one key.
- Run LIS, or one of its variants, on a second key.
The hard part is almost never the LIS call. It is choosing the sort order and the comparison so that "increasing subsequence" means exactly what the original problem means.
Nesting Envelopes
The problem
You are given envelopes as [width, height] pairs. Envelope A fits inside envelope B only if A's width is strictly less than B's width and A's height is strictly less than B's height. You cannot rotate them. What is the largest number of envelopes you can nest one inside another, like Russian dolls?
A nesting chain is a sequence of envelopes that increases strictly in both dimensions. That is a 2D version of LIS. The trick is to remove one dimension by sorting.
Reducing two dimensions to one
Sort the envelopes by width ascending. Any valid chain now appears left to right in the sorted list, so you only need to look for an increasing subsequence of heights.
That alone is not quite right. Two envelopes with the same width cannot nest, but if their heights appear in increasing order after sorting, LIS will happily chain them. The fix is the tie-break: for equal widths, sort by height descending. Within a group of equal widths the heights then form a decreasing run, and a strictly increasing subsequence can take at most one element from a decreasing run. So the LIS can never use two envelopes of the same width.
from bisect import bisect_left
def max_envelopes(envelopes):
# Sort by width ascending, and by height descending for equal widths
envelopes = sorted(envelopes, key=lambda e: (e[0], -e[1]))
tails = []
for _, h in envelopes:
i = bisect_left(tails, h)
if i == len(tails):
tails.append(h)
else:
tails[i] = h
return len(tails)
print(max_envelopes([[5, 4], [6, 4], [6, 7], [2, 3]])) # 3Trace the example. After sorting, the order is (2,3), (5,4), (6,7), (6,4), so the heights are 3, 4, 7, 4. The strict LIS of those heights has length 3 (3, 4, 7), which matches the chain [2,3] → [5,4] → [6,7]. The (6,4) envelope comes after (6,7) because of the descending tie-break, so it cannot extend a chain that already contains a width-6 envelope.
The tie-break failure mode
This is the most common bug in this problem, so it is worth seeing it fail:
from bisect import bisect_left
def lis_strict(seq):
tails = []
for x in seq:
i = bisect_left(tails, x)
if i == len(tails):
tails.append(x)
else:
tails[i] = x
return len(tails)
same_width = [[1, 1], [1, 2], [1, 3]]
wrong = sorted(same_width) # heights 1, 2, 3
right = sorted(same_width, key=lambda e: (e[0], -e[1])) # heights 3, 2, 1
print(lis_strict([h for _, h in wrong])) # 3 (incorrect)
print(lis_strict([h for _, h in right])) # 1 (correct)All three envelopes have width 1, so none can contain another, and the answer is 1. The plain tuple sort gives 3.
Checking against a quadratic reference
When you invent a reduction, test it against a slow solution that follows the problem statement directly. The O(n^2) DP below checks both strict conditions explicitly and needs no clever sort order.
import random
from bisect import bisect_left
def max_envelopes(envelopes):
envelopes = sorted(envelopes, key=lambda e: (e[0], -e[1]))
tails = []
for _, h in envelopes:
i = bisect_left(tails, h)
if i == len(tails):
tails.append(h)
else:
tails[i] = h
return len(tails)
def max_envelopes_quadratic(envelopes):
envs = sorted(envelopes)
n = len(envs)
dp = [1] * n
for i in range(n):
for j in range(i):
if envs[j][0] < envs[i][0] and envs[j][1] < envs[i][1]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp, default=0)
for _ in range(2000):
n = random.randint(0, 12)
envs = [[random.randint(1, 5), random.randint(1, 5)] for _ in range(n)]
assert max_envelopes(envs) == max_envelopes_quadratic(envs), envs
print("all tests passed")The small value range (1 to 5) is deliberate. It produces many ties, and ties are where reductions break.
Variations and decision criteria
Changing the rules changes the sort and the bisect bound. The table summarizes the common versions.
| Nesting rule | Sort key | LIS variant |
|---|---|---|
| Strict in both (`w1 < w2` and `h1 < h2`) | `(w, -h)` | strict, `bisect_left` |
| Non-strict in both (`w1 <= w2` and `h1 <= h2`) | `(w, h)` | non-decreasing, `bisect_right` |
| Strict, rotation allowed | normalize each to `(min, max)`, then `(w, -h)` | strict, `bisect_left` |
In the non-strict case, equal widths are allowed to chain, so you want them in ascending height order, and equal heights are allowed too, so bisect_right is the right bound.
Minimum Deletions to Make a Sequence Sorted
The problem
Given an array, what is the fewest elements you must delete so that the rest is sorted?
Whatever survives the deletions is a subsequence that is sorted. To delete as few as possible, you keep as many as possible. So the answer is:
n - (length of the longest non-decreasing subsequence)if "sorted" means non-decreasing (duplicates allowed side by side).n - (length of the longest strictly increasing subsequence)if "sorted" means strictly increasing.
Pick the variant that matches the problem statement. On arrays with duplicates the two answers differ.
Computing which elements to delete
Often you need the actual elements to remove, not just how many. Reuse the O(n log n) reconstruction, parameterized by the bisect function. Every index not on the rebuilt subsequence gets deleted.
from bisect import bisect_left, bisect_right
def elements_to_delete(a, strict=False):
find = bisect_left if strict else bisect_right
tails_val = []
tails_idx = []
parent = [-1] * len(a)
for i, x in enumerate(a):
k = find(tails_val, x)
if k > 0:
parent[i] = tails_idx[k - 1]
if k == len(tails_val):
tails_val.append(x)
tails_idx.append(i)
else:
tails_val[k] = x
tails_idx[k] = i
keep = set()
i = tails_idx[-1] if tails_idx else -1
while i != -1:
keep.add(i)
i = parent[i]
return [a[j] for j in range(len(a)) if j not in keep]
a = [5, 1, 3, 3, 2, 4]
print(elements_to_delete(a)) # [5, 2] -> keep 1, 3, 3, 4
print(elements_to_delete(a, strict=True)) # [5, 3, 3] -> keep 1, 2, 4
print(elements_to_delete([])) # []For [5, 1, 3, 3, 2, 4], the longest non-decreasing subsequence is 1, 3, 3, 4 (length 4), so you delete 2 elements. The longest strictly increasing subsequence has length 3, so the strict version deletes 3. The strict version can return either 1, 2, 4 or 1, 3, 4 as the kept set. Both are optimal, and the reconstruction returns just one of them.
Related reductions
The same counting idea appears in other forms:
- Minimum deletions to make the array strictly decreasing. Reverse the array, or negate every value, and compute the strict LIS.
- Minimum moves to sort, where one move takes an element out and reinserts it anywhere. The elements you never move must already be in sorted relative order, so the answer is again
n - LNDS(orn - LISfor distinct values). The elements you move are exactly the oneselements_to_deletereturns. - Making an array strictly increasing by changing values, keeping integers. This one is a trap. Kept elements need room for the changed values between them, so
a[j] < a[i]is not enough. You needa[i] - a[j] >= i - j. Transform each element tob[i] = a[i] - iand take the longest non-decreasing subsequence ofb. The answer isn - LNDS(b).
| Problem | Transform | Variant | Answer |
|---|---|---|---|
| Delete to non-decreasing | none | `bisect_right` | `n - L` |
| Delete to strictly increasing | none | `bisect_left` | `n - L` |
| Delete to strictly decreasing | negate values | `bisect_left` | `n - L` |
| Change values to strictly increasing integers | `b[i] = a[i] - i` | `bisect_right` | `n - L` |
| Max non-crossing bridges between two banks | sort pairs by first bank | strict on second bank | `L` |
Common Errors
- Wrong tie-break order in 2D problems. Equal first keys must be ordered so the LIS cannot chain them when the rules forbid it (descending second key for strict rules).
- Mismatched strictness. Using
bisect_leftfor a "non-decreasing" requirement undercounts the kept elements whenever duplicates exist, so you report too many deletions. - Forgetting the empty input.
tails_idx[-1]raisesIndexErroron an empty list. Guard it, as the code above does. - Assuming the kept subsequence is unique. Many optimal answers can exist. If a test expects one specific subsequence, the problem must say how to break ties, for example the lexicographically smallest one, and plain reconstruction does not guarantee that.
Exercise
Envelopes are [[3, 3], [3, 5], [4, 4], [4, 6], [5, 5]] with strict nesting in both dimensions. List the height sequence after sorting with key (w, -h), and give the maximum nesting depth.
Show answer
Sorted order is (3,5), (3,3), (4,6), (4,4), (5,5), so heights are 5, 3, 6, 4, 5. The strict LIS is 3, 4, 5 with length 3, matching the chain [3,3] → [4,4] → [5,5].
Exercise
For a = [2, 2, 2, 1], how many deletions make it non-decreasing, and how many make it strictly increasing?
Show answer
The longest non-decreasing subsequence is 2, 2, 2 (length 3), so 1 deletion. The longest strictly increasing subsequence has length 1, so 3 deletions.
Exercise
Envelopes may be rotated before nesting, and nesting is strict in both dimensions. Why does normalizing each envelope to (min side, max side) give the correct answer?
Show answer
If A fits in B under some rotation, then A's shorter side is less than B's shorter side and A's longer side is less than B's longer side. Matching short to short and long to long is always the best way to orient them. After normalizing, the problem is the ordinary non-rotating version, solved with key (w, -h) and bisect_left.
Exercise
Why is the answer for a = [1, 2, 2, 3] under "change the fewest values so the array is strictly increasing integers" equal to 1, and how does the b[i] = a[i] - i transform show it?
Show answer
b = [1, 1, 0, 0]. Its longest non-decreasing subsequence has length 2 (for example 1, 1, or 0, 0), so the formula gives 4 - 2 = 2 changes, not 1. Check by hand: keeping 1, 2, 3 at indices 0, 1, 3 fails because index 2 would need a value strictly between 2 and 3. Keeping 1 and 2 at indices 0 and 1 and changing the rest to 3 and 4 works, so the true answer is 2. The question's claim of 1 is wrong, and the transform catches the gap that plain LIS (which keeps 3 elements) misses.