KatInterview

Cancel Neighboring Letter Pairs in a String

Stacks & QueuesAuto-graded · 23 test cases
EasyAuto-gradedStacks & Queuesstackstringsimulation

Last updated

Tests using a stack to repeatedly cancel adjacent equal characters in a string, including cascading cancellations, in linear time.

You are given a string s made of lowercase English letters. Apply the following operation as many times as possible:

  • Find two neighboring positions that hold the same letter and delete both of them. The remaining letters close the gap and become neighbors.

Keep going until no two neighboring letters are equal. Return the string that remains.

Removing a pair can bring two other equal letters next to each other, so deletions may cascade. The final string does not depend on which pair you choose to delete first.

If every letter is eventually removed, return the empty string "".

Constraints

  • 0 <= len(s) <= 200000
  • s contains only lowercase English letters (a to z).
  • The input may be empty, in which case the result is "".
  • The solution should run in roughly linear time in len(s).

Examples

Example 1

Input: cancel_adjacent_pairs('abbaca')

Output: 'ca'

Hints

Hint 1

Rescanning the string after every deletion is too slow for 200,000 characters. Think about processing the string in a single left-to-right pass.

Hint 2

At any moment, only the most recently kept character can cancel with the incoming one. What structure gives you quick access to the latest kept character and lets you remove it?

Hint 3

Use a stack. If the incoming character equals the top, pop the top. Otherwise push the incoming character. Join the stack at the end rather than building the string by repeated concatenation.