Implement the removeAdjacentDuplicates method that removes adjacent duplicate characters using stack-style processing.

The input contains a string text. Your task is to repeatedly remove adjacent duplicate characters until no adjacent duplicate pair remains.

When two equal characters appear next to each other, both characters should be removed. After removal, the remaining characters join together, and this may create a new adjacent duplicate pair. For example, abbaca becomes ca.

Example 1

Input
text (string) = abbaca
Returns (string) ca

Example 2

Input
text (string) = azxxzy
Returns (string) ay

Example 3

Input
text (string) = abc
Returns (string) abc

Use a stack-like result string to process characters from left to right.

For each character, compare it with the last character currently stored in the result. If both are the same, remove the last character because the pair cancels out. Otherwise, add the current character to the result.

After all characters are processed, the result contains the final string with all possible adjacent duplicates removed.

Pseudocode:

function removeAdjacentDuplicates(text):
    result = empty stack
    for each character ch in text:
        if result is not empty and top of result == ch:
            remove top from result
        else:
            push ch into result
    return characters of result as string
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.