Chat app~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-1963greedy
You work on a chat app that sends templated messages. A template holds fields in curly braces, such as {name}, and the braces must match: every { is closed by a later }.
A broken template has the right number of each brace, but some are in the wrong places. A repair tool can swap any two characters. Your team lead asks: "How many swaps does the repair tool need, at the fewest, to fix a template?"
Write fewest_swaps(braces).
braces is a string of { and } with the same number of each, so its length is even.} has an earlier { that it closes, with none left over.Input: braces = "}}}{{{"
Output: 2Scan from the left. Count the } that have no open { waiting. A swap can fix two of them at once, so the answer is that count divided by 2, rounded up.
| Character | Open { waiting |
Unmatched } |
|---|---|---|
| } | 0 | 1 |
| } | 0 | 2 |
| } | 0 | 3 |
| { | 1 | 3 |
| { | 2 | 3 |
| { | 3 | 3 |
There are 3 unmatched closing braces, so the answer is 2: swap the first and last characters, then swap the second and fifth.
Input: braces = "}{}{"
Output: 1One } is unmatched. Swapping the first and last characters gives {}{}, which matches. One swap is enough.
Input: braces = "{}{}"
Output: 0The template already matches, so no swap is needed.
2 ≤ len(braces) ≤ 100,000, and the length is evenbraces holds only { and }, with the same number of eachThe template can have 100,000 characters. A single swap has about 5 billion choices, and the best sequence of swaps is a search over many of them. One pass that counts costs 100,000 steps.