Files
usaco/concepts/lexicographic-greedy-construction/concept.md
T

208 lines
22 KiB
Markdown

<!-- concept tags=greedy,strings,monotonic-stack,lexicographic -->
# Lexicographically largest answers: greedy construction
_Build the lexicographically largest answer position by position, at each step taking the largest choice that can still be completed. The classic instance is a monotonic stack that finds the largest length-k subsequence in O(n)._
_Explained by claude-opus-5-5 on 20 October 2026._
## Intuition
### The one fact everything rests on
Lexicographic order compares two sequences at their **first differing position**, and nothing after that position matters. So making position 1 as large as possible beats any improvement you could make later. Once position 1 is fixed, the same holds for position 2, and so on.
Every "lexicographically largest answer" problem therefore reduces to one rule:
$$\text{answer}_j = \max\{\, c : \text{the prefix } \text{answer}_1 \dots \text{answer}_{j-1}\, c \text{ can still be completed to a valid answer} \,\}$$
In words: decide positions left to right. At each one, take the largest choice that still leaves *some* way to finish.
### Why the obvious approaches fail
- **Enumerating all valid answers and taking the max** is exponential.
- **Greedy without a feasibility check**, meaning "just take the biggest thing now", walks into dead ends. For a length-$k$ subsequence of `cabde` with $k=3$, grabbing `e` first leaves nothing to fill the other two slots.
- **Sorting by a naive key** is also wrong. To build the largest number from the strings {9, 34, 3}, plain descending order gives `9343`, but the right answer is `9334`.
### What the real work is
The skill is building a **fast feasibility check**, and then often replacing "try every candidate per position" with a structure that finds the best feasible candidate directly. For subsequences that structure is a monotonic stack: one pass, $O(n)$ total.
### The edge case to watch
When lengths can differ, a proper prefix is *smaller*: `ab` < `abc`. So when length is free, "largest" also means "longer is better on ties", and "smallest" means "shorter is better".
## How it works
### The general recipe
1. **Pin down the order.** Decide whether the answer length is fixed or free, and whether you compare characters, integers or something else.
2. **Write a feasibility check.** `feasible(prefix)` answers whether some valid full answer starts with this prefix. It is usually a counting argument, such as "enough elements remain" or "enough copies of each letter remain". Sometimes it is a matching or a flow.
3. **Build the answer greedily.**
- For each position, try candidates from largest to smallest.
- Keep the first candidate that leaves the prefix feasible.
- Trying in that order guarantees the first one that works is the best one.
4. **Speed it up.**
- The naive cost is $O(L \cdot |\Sigma| \cdot T_{check})$.
- The usual fix is a structure that answers "largest feasible candidate" directly: a monotonic stack, a suffix maximum, a heap, or a segment tree over a window.
### The canonical case: the largest subsequence of length exactly $k$
**The window view.** For pick $j$ (0-based), the element must come from index $\text{last}+1$ up to $n-k+j$, where $\text{last}$ is the index of the previous pick. Going further right would leave too few elements for the remaining picks. Inside that window, take the maximum, choosing the leftmost copy if there are ties. This is correct but costs $O(nk)$.
**The stack view** does the same work in $O(n)$:
- `st` holds the current best prefix of the answer, built from `s[0..i-1]`, that can still be extended to length `k`.
- Before pushing `s[i]`, pop while all three hold:
- `!st.empty()` and `st.back() < s[i]`. Putting `s[i]` in the top's slot makes the answer larger at an *earlier* position, and that beats anything that happens later.
- `st.size()-1 + (n-i) >= k`.
- `st.size()-1` is how many elements would stay kept after the pop.
- `n-i` is how many elements remain to choose from, counting `s[i]` itself.
- If their sum drops below `k`, popping would make a length-`k` answer impossible. The top is then *forced* and must stay.
- Then push `s[i]` only if `st.size() < k`. If the stack is full, every pop was blocked by `st.back() >= s[i]`. Since `n-i >= 1`, the counting condition holds whenever the stack is full, so it cannot be what blocked the pop. Skipping `s[i]` therefore loses nothing.
**Why the stack is correct (exchange argument).**
- Suppose the final answer keeps `x` at some slot, and a later element `c > x` could have taken that slot with enough elements left over.
- Then the answer with `c` in that slot is strictly larger, which contradicts optimality.
- The stack makes exactly that swap whenever it is legal, and only when it is legal.
### Other shapes of the same rule
- **Largest number from concatenating strings:** sort with the comparator `a+b > b+a`. Putting `a` before `b` is better exactly when that concatenation wins at the first difference.
- **Largest topological order:** run Kahn's algorithm with a max-heap, always taking the largest available vertex.
- **Largest permutation with at most $k$ swaps:** walk left to right and swap the largest remaining value into the current position.
## Walkthrough
**Step 1.** **The greedy rule, by windows.**
- The task: the largest subsequence of length $k=3$ of `s = cabde`, with $n=5$.
- Pick 1 must leave 2 elements after it, so it comes from indices $[0, n-k] = [0,2]$. The maximum there is `c`.
- Pick 2 comes from $[1,3]$, giving `d`. Pick 3 comes from $[4,4]$, giving `e`.
- The answer is `cde`.
This is correct but costs $O(nk)$. The stack in the next steps reaches the same answer in one pass.
```svg
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 320'><text x='20' y='68' font-family='sans-serif' font-size='14' fill='currentColor'>s</text><rect x='60' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='124' y='40' width='56' height='44' fill='#f59e0b' fill-opacity='0.35' stroke='currentColor'/><rect x='188' y='40' width='56' height='44' fill='#f59e0b' fill-opacity='0.35' stroke='currentColor'/><rect x='252' y='40' width='56' height='44' fill='none' stroke='currentColor'/><rect x='316' y='40' width='56' height='44' fill='none' stroke='currentColor'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='88' y='69'>c</text><text x='152' y='69'>a</text><text x='216' y='69'>b</text><text x='280' y='69'>d</text><text x='344' y='69'>e</text></g><g font-family='ui-monospace, monospace' font-size='13' fill='currentColor' text-anchor='middle'><text x='88' y='102'>0</text><text x='152' y='102'>1</text><text x='216' y='102'>2</text><text x='280' y='102'>3</text><text x='344' y='102'>4</text></g><path d='M60 110 v8 h184 v-8' fill='none' stroke='#f59e0b' stroke-width='2'/><g font-family='sans-serif' font-size='14' fill='currentColor'><text x='20' y='160'>pick 1: window [0,2] → max c at 0</text><text x='20' y='188'>pick 2: window [1,3] → max d at 3</text><text x='20' y='216'>pick 3: window [4,4] → e</text><text x='20' y='256'>answer = cde (k = 3, n = 5)</text></g></svg>
```
**Step 2.** **Stack pass, i = 0 and i = 1.**
- At $i=0$ the stack is empty, so `c` is pushed.
- At $i=1$ the top is `c` and the current element is `a`. Since `c` ≥ `a`, the condition `st.back() < s[i]` fails and nothing is popped.
- The stack has room ($2 < k$), so `a` is pushed.
The stack is now `[c, a]`. It is the best prefix of the answer so far that can still be completed.
```svg
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 320'><text x='20' y='68' font-family='sans-serif' font-size='14' fill='currentColor'>s</text><rect x='60' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='124' y='40' width='56' height='44' fill='#3b82f6' fill-opacity='0.4' stroke='currentColor'/><rect x='188' y='40' width='56' height='44' fill='none' stroke='currentColor'/><rect x='252' y='40' width='56' height='44' fill='none' stroke='currentColor'/><rect x='316' y='40' width='56' height='44' fill='none' stroke='currentColor'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='88' y='69'>c</text><text x='152' y='69'>a</text><text x='216' y='69'>b</text><text x='280' y='69'>d</text><text x='344' y='69'>e</text></g><g font-family='ui-monospace, monospace' font-size='13' fill='currentColor' text-anchor='middle'><text x='88' y='102'>0</text><text x='152' y='102'>1</text><text x='216' y='102'>2</text><text x='280' y='102'>3</text><text x='344' y='102'>4</text></g><path d='M152 112 l-7 12 h14 z' fill='#3b82f6'/><text x='152' y='142' font-family='ui-monospace, monospace' font-size='14' fill='currentColor' text-anchor='middle'>i</text><text x='20' y='228' font-family='sans-serif' font-size='14' fill='currentColor'>stack</text><rect x='100' y='200' width='56' height='44' fill='none' stroke='currentColor'/><rect x='164' y='200' width='56' height='44' fill='#3b82f6' fill-opacity='0.4' stroke='currentColor'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='128' y='229'>c</text><text x='192' y='229'>a</text></g><g font-family='sans-serif' font-size='14' fill='currentColor'><text x='20' y='282'>i=0: push c</text><text x='20' y='306'>i=1: top c ≥ a → no pop, push a</text></g></svg>
```
**Step 3.** **i = 2, current `b`.**
- The top `a` is smaller than `b`.
- Counting check: `st.size()-1 + (n-i)` = $1 + 3 = 4 \ge 3$, so enough elements remain without `a`. Pop `a`.
- The new top is `c`, and `c` ≥ `b`, so popping stops.
- Push `b`. The stack is `[c, b]`.
Slot 2 got upgraded from `a` to `b`, and that beats anything later positions could do.
```svg
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 320'><text x='20' y='68' font-family='sans-serif' font-size='14' fill='currentColor'>s</text><rect x='60' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='124' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='188' y='40' width='56' height='44' fill='#3b82f6' fill-opacity='0.4' stroke='currentColor'/><rect x='252' y='40' width='56' height='44' fill='none' stroke='currentColor'/><rect x='316' y='40' width='56' height='44' fill='none' stroke='currentColor'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='88' y='69'>c</text><text x='152' y='69'>a</text><text x='216' y='69'>b</text><text x='280' y='69'>d</text><text x='344' y='69'>e</text></g><g font-family='ui-monospace, monospace' font-size='13' fill='currentColor' text-anchor='middle'><text x='88' y='102'>0</text><text x='152' y='102'>1</text><text x='216' y='102'>2</text><text x='280' y='102'>3</text><text x='344' y='102'>4</text></g><path d='M216 112 l-7 12 h14 z' fill='#3b82f6'/><text x='216' y='142' font-family='ui-monospace, monospace' font-size='14' fill='currentColor' text-anchor='middle'>i</text><text x='20' y='228' font-family='sans-serif' font-size='14' fill='currentColor'>stack</text><rect x='100' y='200' width='56' height='44' fill='none' stroke='currentColor'/><rect x='164' y='200' width='56' height='44' fill='#3b82f6' fill-opacity='0.4' stroke='currentColor'/><rect x='400' y='200' width='56' height='44' fill='none' stroke='#ef4444' stroke-width='2' stroke-dasharray='5 3'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='128' y='229'>c</text><text x='192' y='229'>b</text><text x='428' y='229'>a</text></g><text x='470' y='228' font-family='sans-serif' font-size='14' fill='currentColor'>popped</text><g font-family='sans-serif' font-size='14' fill='currentColor'><text x='20' y='282'>a &lt; b and 1 + 3 = 4 ≥ 3 → pop a</text><text x='20' y='306'>c ≥ b → stop, push b</text></g></svg>
```
**Step 4.** **i = 3, current `d`.**
- The top `b` < `d`, and $1 + 2 = 3 \ge 3$, so pop `b`.
- Now the top `c` < `d` too, but the check gives $0 + 2 = 2 < 3$.
- Dropping `c` would leave only `d` and `e`, too few for length 3.
- So `c` is **forced** and stays. This is exactly why the greedy cannot simply start with `d`.
- Push `d`. The stack is `[c, d]`.
```svg
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 320'><text x='20' y='68' font-family='sans-serif' font-size='14' fill='currentColor'>s</text><rect x='60' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='124' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='188' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='252' y='40' width='56' height='44' fill='#3b82f6' fill-opacity='0.4' stroke='currentColor'/><rect x='316' y='40' width='56' height='44' fill='none' stroke='currentColor'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='88' y='69'>c</text><text x='152' y='69'>a</text><text x='216' y='69'>b</text><text x='280' y='69'>d</text><text x='344' y='69'>e</text></g><g font-family='ui-monospace, monospace' font-size='13' fill='currentColor' text-anchor='middle'><text x='88' y='102'>0</text><text x='152' y='102'>1</text><text x='216' y='102'>2</text><text x='280' y='102'>3</text><text x='344' y='102'>4</text></g><path d='M280 112 l-7 12 h14 z' fill='#3b82f6'/><text x='280' y='142' font-family='ui-monospace, monospace' font-size='14' fill='currentColor' text-anchor='middle'>i</text><text x='20' y='228' font-family='sans-serif' font-size='14' fill='currentColor'>stack</text><rect x='100' y='200' width='56' height='44' fill='#f59e0b' fill-opacity='0.35' stroke='currentColor'/><rect x='164' y='200' width='56' height='44' fill='#3b82f6' fill-opacity='0.4' stroke='currentColor'/><rect x='400' y='200' width='56' height='44' fill='none' stroke='#ef4444' stroke-width='2' stroke-dasharray='5 3'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='128' y='229'>c</text><text x='192' y='229'>d</text><text x='428' y='229'>b</text></g><text x='470' y='228' font-family='sans-serif' font-size='14' fill='currentColor'>popped</text><text x='100' y='190' font-family='sans-serif' font-size='13' fill='currentColor'>forced</text><g font-family='sans-serif' font-size='14' fill='currentColor'><text x='20' y='282'>b &lt; d and 1 + 2 = 3 ≥ 3 → pop b</text><text x='20' y='306'>c &lt; d but 0 + 2 = 2 &lt; 3 → blocked, push d</text></g></svg>
```
**Step 5.** **i = 4, current `e`.**
- The top `d` < `e`, but the check gives $1 + 1 = 2 < 3$, so the pop is blocked.
- Push `e`. The stack is `[c, d, e]`.
- That matches the window greedy's answer, `cde`.
Every element was pushed once and popped at most once, so the pass is $O(n)$.
```svg
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 320'><text x='20' y='68' font-family='sans-serif' font-size='14' fill='currentColor'>s</text><rect x='60' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='124' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='188' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='252' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='316' y='40' width='56' height='44' fill='#3b82f6' fill-opacity='0.4' stroke='currentColor'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='88' y='69'>c</text><text x='152' y='69'>a</text><text x='216' y='69'>b</text><text x='280' y='69'>d</text><text x='344' y='69'>e</text></g><g font-family='ui-monospace, monospace' font-size='13' fill='currentColor' text-anchor='middle'><text x='88' y='102'>0</text><text x='152' y='102'>1</text><text x='216' y='102'>2</text><text x='280' y='102'>3</text><text x='344' y='102'>4</text></g><path d='M344 112 l-7 12 h14 z' fill='#3b82f6'/><text x='344' y='142' font-family='ui-monospace, monospace' font-size='14' fill='currentColor' text-anchor='middle'>i</text><text x='20' y='228' font-family='sans-serif' font-size='14' fill='currentColor'>stack</text><rect x='100' y='200' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='164' y='200' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='228' y='200' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='128' y='229'>c</text><text x='192' y='229'>d</text><text x='256' y='229'>e</text></g><g font-family='sans-serif' font-size='14' fill='currentColor'><text x='20' y='282'>d &lt; e but 1 + 1 = 2 &lt; 3 → blocked, push e</text><text x='20' y='306'>result = cde</text></g></svg>
```
## Using it
```cpp
string s = "cabde";
string best = largestSubseq(s, 3); // "cde"
vector<int> a = {3, 9, 5, 9, 1};
vector<int> b = largestSubseq(a, 2); // {9, 9}
string num = largestConcat({"9", "34", "30", "5", "3"}); // "9534330"
// smallest subsequence of length k: reuse with negated values,
// or copy largestSubseq and flip < to >
```
## Complexity
- **Monotonic stack, `largestSubseq`:** $O(n)$ time. Each element is pushed at most once and popped at most once, so the inner `while` runs at most $n$ times in total. Memory is $O(n)$ for the stack, and at most $k$ elements are kept.
- **Generic position-by-position greedy:** $O(L \cdot |\Sigma| \cdot T_{check})$ time, where $L$ is the answer length, $|\Sigma|$ is the number of candidates per position and $T_{check}$ is the cost of one feasibility check. Use [complexity-budget-estimation] to decide whether it fits or needs a faster check.
- **Window-max version:** $O(k \log n)$ time with a segment tree or sparse table, or $O(n)$ with a monotonic deque.
- **`largestConcat`:** $O(n \log n \cdot \ell)$ time, where $\ell$ is the string length, because each comparison builds two concatenations.
## When to reach for it
### Signals in the statement
- "Lexicographically largest/smallest", "maximum number you can form", "print the answer that comes first in dictionary order", or "if there are multiple answers, print the lexicographically smallest".
- The answer is a sequence built under constraints: pick a subsequence, delete some characters, order some items, or assign values position by position.
### The decision process
1. Can you check "is this prefix completable?" quickly? If so, the position-by-position greedy works.
2. Is it a subsequence with a length or count constraint? Use the **monotonic stack**.
3. Is it an ordering of pieces? Use a **sort with a pairwise comparator**, such as `a+b > b+a`.
4. Is it an ordering with precedence constraints? Use **Kahn's algorithm with a heap**.
5. Is the choice per position a range maximum over a sliding window? Use a **sparse table, segment tree or deque**.
### Close alternatives
- **DP plus reconstruction.** When feasibility itself needs DP, as in the lexicographically smallest LCS or path, first compute `can[i][state]` or `best[i]` from the back. Then walk forward and pick the smallest or largest option whose DP value is still optimal.
- **Suffix arrays or hashing.** When you must compare long candidate substrings quickly rather than build an answer, as in the largest rotation or the largest substring.
- **Binary search on the answer.** Usable only when the objective is a number. Lexicographic order on sequences is not a single numeric threshold.
## Pitfalls
- **Ignoring the prefix rule.** `"ab" < "abc"`. If the answer length is free, a largest answer should keep tied elements, so pop only on strict `<`. A smallest answer, by contrast, prefers stopping early.
- **Comparing numbers as strings or strings as numbers.** `"9" > "10"` as strings, while `9 < 10` as ints. Know which order the problem means, and use `vector<int>` for integer sequences.
- **Off-by-one in the counting check.** `n-i` must count `s[i]` itself, and `st.size()-1` is the count *after* the pop. Writing `n-i-1` or `st.size()` either blocks valid pops or allows answers shorter than `k`.
- **Forgetting the push cap `st.size() < k`.** Without it the stack returns more than `k` elements.
- **Greedy with no feasibility check.** Taking the biggest element now can make the rest of the answer impossible. Always ask: can I still finish?
- **Non-strict comparator in `sort`.** Using `a+b >= b+a` breaks strict weak ordering, which is undefined behaviour and can crash. Use a strict `>`.
- **Topological-order trap.** A max-heap Kahn gives the lexicographically largest *sequence*. "Give the smallest labels to the earliest positions" is a different objective: reverse the graph, use a max-heap, and reverse the result.
- **Tie-breaking in the window greedy.** When the maximum appears several times in a window, take the **leftmost** copy. That leaves the most room for the later picks.
- **Multi-test reset.** Clear the stack, count arrays and `inStack` flags between test cases.
## Variations
- **Smallest instead of largest:** flip the comparison in the pop condition to `st.back() > s[i]`. This is "Remove K Digits": keep $n-k$ digits, then strip leading zeros if the problem asks.
- **Length is free:** drop the counting check and the push cap. Pop while `st.back() < s[i]`, then always push. The result is the non-increasing chain of suffix maxima, with ties kept because longer wins on ties.
- **Each distinct letter exactly once** (largest or smallest such subsequence):
- Precompute `last[c]`, the last index of each letter, and keep an `inStack[c]` flag.
- Skip a letter if it is already in the stack.
- Pop the top only if it is beaten and `last[top] > i`, meaning it appears again later.
- **Elements from two arrays, keeping each one's internal order** ("Create Maximum Number"):
- For each split $k = k_1 + k_2$, take `largestSubseq` of both arrays.
- Merge them greedily, at each step taking from whichever *remaining suffix* is lexicographically larger.
- **General per-position constraint:** use the window form. Each pick is a range-maximum query over the allowed indices, so a sparse table or segment tree gives $O(k \log n)$. A monotonic deque works when the window only slides right.
- **Largest permutation or topological order:** use a max-heap of currently available elements, as in Kahn's algorithm. For "largest with at most $k$ swaps", keep a position map so you can swap the largest remaining value forward.
- **Expensive feasibility:** if feasibility is monotone in the candidate, binary search the largest feasible value for each position instead of trying every candidate.