Remove adjacent duplicate groups repeatedly
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: Remove adjacent duplicate groups repeatedly evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 0 <= len(s) <= 10^5
- s consists of printable characters (lowercase English letters in the examples)
- Deletions cascade: removing a group can create a new deletable group from the now-adjacent neighbours
- Return the empty string if everything is deleted
Examples
Input: ("abbba",)
Expected Output: ""
Explanation: Delete "bbb" -> "aa", then delete "aa" -> empty string.
Input: ("aabccba",)
Expected Output: "a"
Explanation: Delete "aa" -> "bccba", delete "cc" -> "bba", delete "bb" -> "a".
Input: ("deeedbbcccbdaa",)
Expected Output: "bd"
Explanation: Delete eee -> ddbbcccbdaa, delete dd -> bbcccbdaa, delete bb -> cccbdaa, delete ccc -> bdaa, delete aa -> bd; no group of length >= 2 remains.
Input: ("",)
Expected Output: ""
Explanation: Empty input stays empty.
Input: ("a",)
Expected Output: "a"
Explanation: A single character has no group of length >= 2, so it survives.
Input: ("abcde",)
Expected Output: "abcde"
Explanation: All runs have length 1; nothing is deleted.
Input: ("aaaa",)
Expected Output: ""
Explanation: One maximal group of length 4 (>= 2) is deleted entirely.
Input: ("aaabbbaaa",)
Expected Output: ""
Explanation: Delete aaa -> bbbaaa, delete bbb -> aaa, delete aaa -> empty: cascading deletions clear the whole string.
Hints
- Maintain a stack of (character, run-length) pairs as you scan left to right, accumulating consecutive equal characters into the top entry.
- A run is only ever deletable once you know it is complete. Finalize the top run when a different character arrives (or at end of string): if its length is >= 2, pop it.
- Popping a >= 2 run exposes the previous survivor, which may equal the incoming character and merge with it — keep checking the new top against the incoming char so deletions cascade correctly.
- After the scan, the final top run and any merges it triggers must also be collapsed; every group below the top is guaranteed to have length 1, so collapsing only ever happens at the top.