Repeatedly Remove Adjacent Equal Characters
Company: Omnissa
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates a candidate's ability to use a stack-based approach to repeatedly cancel out adjacent equal elements in a string. It tests understanding of amortized linear-time string processing and how local reductions can cascade into new matches, a common pattern in coding interviews. The problem is a practical, implementation-focused algorithms exercise rather than a purely conceptual one.
Constraints
- 1 <= s.length <= 100000
- s consists only of lowercase English letters ('a'-'z').
- Return the final string after all possible removals; it may be empty.
- Aim for a single linear pass over the input.
Examples
Input: ("abbaca",)
Expected Output: "ca"
Explanation: Remove adjacent 'bb' -> 'aaca', then 'aa' -> 'ca'. No adjacent equal pair remains.
Input: ("azxxzy",)
Expected Output: "ay"
Explanation: Remove 'xx' -> 'azzy', then 'zz' -> 'ay'.
Input: ("aaaa",)
Expected Output: ""
Explanation: Two pairs of 'aa' cancel completely, leaving the empty string.
Input: ("abc",)
Expected Output: "abc"
Explanation: No adjacent equal pair exists, so the string is unchanged.
Input: ("a",)
Expected Output: "a"
Explanation: A single character has no adjacent pair and is returned as-is.
Input: ("aabccba",)
Expected Output: "a"
Explanation: 'aa' cancels -> 'bccba'; 'cc' cancels -> 'bba'; 'bb' cancels -> 'a'.
Input: ("mississippi",)
Expected Output: "m"
Explanation: Repeated cascading cancellations of 'ss', 'ii', and 'pp' collapse everything except the leading 'm'.
Hints
- Process the string left to right and keep the characters that survive so far in a stack.
- For each new character, if it equals the character on top of the stack, they cancel out: pop the top instead of pushing. Otherwise push the new character.
- The stack naturally handles cascading removals: after a pop, the newly exposed top can immediately cancel with the next character. Join the stack at the end for the answer.