Sub topic 9
Applications: Nesting Envelopes and Minimum Deletions
This chapter assumes you can already write the O(n log n) tails-array LIS and know when to use bisect_left and when to use bisect_right. Here we take two common problems and turn each one into an LIS problem. Once the input is in the right shape, the algorithm you already have does the rest.
Minimum Deletions to Make a Sequence Sorted
Suppose you must delete as few elements as possible so that the remaining sequence is sorted. Every element you keep belongs to a sorted subsequence. To delete the fewest elements, keep the longest sorted subsequence and delete everything else:
- To make the sequence strictly increasing, delete
n - LIS(a)elements. - To make the sequence non-decreasing, delete
n - LNDS(a)elements, where LNDS is the longest non-decreasing subsequence.
The only thing that changes between the two cases is the binary search bound.
from bisect import bisect_left, bisect_right
def longest_sorted(a, strict=True):
search = bisect_left if strict else bisect_right
tails = []
for x in a:
i = search(tails, x)
if i == len(tails):
tails.append(x)
else:
tails[i] = x
return len(tails)
def min_deletions(a, strict=True):
return len(a) - longest_sorted(a, strict)
print(min_deletions([5, 1, 3, 2, 4])) # 2 (keep 1, 3, 4)
print(min_deletions([1, 3, 3, 2, 3], strict=False)) # 1 (keep 1, 3, 3, 3)
print(min_deletions([1, 3, 3, 2, 3], strict=True)) # 2 (keep 1, 2, 3)Nesting Envelopes
You are given envelopes as [width, height] pairs. One envelope fits inside another only if it is strictly smaller in both width and height. The task is to find the largest number of envelopes you can nest one inside another.
This is LIS in two dimensions. The standard approach makes it one-dimensional:
- Sort the envelopes by width, ascending.
- For equal widths, sort by height, descending.
- Run strictly increasing LIS on the heights.
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]])) # 3Why the Descending Tie-Break Matters
Once the envelopes are sorted by width, any increasing run of heights looks like a valid nesting chain. That only holds if no two envelopes in the chain share a width. Look at what each tie-break does to the same input:
| Sort order | Height sequence | Strict LIS | Result |
|---|---|---|---|
| `(w, h)` ascending | 3, 4, 4, 7 | 3, 4, 7 (length 3) | Correct by luck |
| `(w, h)` ascending on `[[6,4],[6,7]]` | 4, 7 | 4, 7 (length 2) | Wrong: same width cannot nest |
| `(w, -h)` | 7, 4 | length 1 | Correct |
With descending heights inside each width group, the heights in a group can never form an increasing pair, so the LIS picks at most one envelope per width. Strictness in width is now handled by the sort. Strictness in height is handled by bisect_left.
Common Errors
- You sort only by width and leave the order of equal widths to chance. The answer is then wrong only on some inputs, which makes the bug hard to find.
- You run the O(n²) DP. It is correct, but typical limits (around 10⁵ envelopes) make it too slow.
- You forget that the tails array is not the actual nesting chain. If you need the envelopes themselves, use the parent-pointer reconstruction from the earlier chapter on the sorted list.
Exercise
What does max_envelopes return for [[1, 1], [1, 2], [2, 3], [3, 3]]? Trace the sorted order and the height sequence.
Show answer
The sorted order is [1,2], [1,1], [2,3], [3,3], so the heights are 2, 1, 3, 3. The strict LIS has length 2, for example 1, 3. The function returns 2: [1,1] fits inside [2,3], but [2,3] cannot fit inside [3,3] because their heights are equal.
Exercise
For a = [3, 1, 2, 2, 4], how many deletions are needed to make it strictly increasing, and how many to make it non-decreasing?
Show answer
The strict LIS is 1, 2, 4 with length 3, so 5 - 3 = 2 deletions. The longest non-decreasing subsequence is 1, 2, 2, 4 with length 4, so 5 - 4 = 1 deletion.