Remove All Adjacent Duplicates in String II
Real-world version: Token Tape CompactorThe statement here is our own: the same inputs, outputs and technique.
A tape of tokens is written as the lowercase string s. A compactor works on it one step at a time.
A step picks any spot where k neighbouring tokens all carry the same letter, lifts exactly those k tokens off the tape, and lets the two loose ends join, which may put fresh neighbours side by side. Steps keep going while some spot still has k matching neighbours.
Whichever spots the compactor picks, the tape it finishes with is the same, so return that final tape as a string. It may be empty.
Examples
Example 1
- Input
- s = "abbbaaac", k = 3
- Output
- "ac"
Lifting the three `b` tokens joins the leading `a` to the three that followed them, giving `aaaac`. Three of those four `a` tokens then come off, leaving `ac`, which has no spot with three matching neighbours.
Example 2
- Input
- s = "aaaa", k = 3
- Output
- "a"
One step removes three of the four `a` tokens. A single `a` is left and no further step applies.
Example 3
- Input
- s = "ppqqppqq", k = 2
- Output
- ""
Removing the leading `pp` leaves `qqppqq`; removing that `qq` leaves `ppqq`, then `qq`, then nothing at all.
Constraints
- 1 <= s.length <= 10^5
- 2 <= k <= 10^4
- s holds lowercase English letters only.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def remove_duplicates(s: str, k: int) -> str:public String removeDuplicates(String s, int k)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's