We have a string of lowercase letters, and whenever two identical letters sit next to each other, we remove both of them. After removing a pair, the letters that were on either side of the removed pair become new neighbors, and they might form a new duplicate pair themselves. So one removal can trigger a chain of further removals.
This "remove a pair, then react to the new neighbors" behavior maps onto a stack. As we read the string left to right, the stack holds the characters that have survived so far. A new character either cancels the most recent survivor (if they are equal) or joins it. That lets us resolve every pair in a single pass instead of repeatedly rescanning the string.
1 <= s.length <= 10^5: with up to 100,000 characters, an O(n^2) approach that rescans the whole string after each removal does roughly 5 billion operations in the worst case, which is too slow. We want a single-pass O(n) solution.s consists of lowercase English letters only. There are no special characters to handle, and equality of two characters is a single comparison.Simulate exactly what the problem describes: scan the string for an adjacent duplicate, remove the first pair found, and repeat until no pair remains.
This is correct but inefficient. Every removal restarts the scan from the beginning, because deleting a pair can create a new pair just before the deletion point. A string of nested pairs like "aabb...zz" forces one full scan per removal.
s[i] == s[i+1].i and i+1.The bottleneck is restarting the scan from the beginning after every removal. The next approach resolves each pair the moment it forms, in a single left-to-right pass.
Check for duplicates as we build the result instead of hunting for them afterward. Process characters left to right. Before placing a character, compare it to the last character already placed. If they are equal, they form an adjacent pair, so remove the placed character and discard the new one. Otherwise, place the new character.
The stack holds the characters that have survived so far. Each new character either cancels the top of the stack or gets pushed onto it. After processing every character, the stack contains the final string.
The reason a single left-to-right pass catches every removal, including chained ones, is the invariant: the stack never contains two equal adjacent characters. When a pop happens, the new top is whatever sat beneath the removed character, which is now adjacent to the next character we process. If those two are equal, the very next comparison removes them too. A character once popped is gone for good, so no removal can be missed and none needs revisiting.
c in the string:c, pop the top element (the pair cancels out).c onto the stack.