Remove All Adjacent Duplicates

easy Strings

Problem

Repeatedly remove two equal letters that stand next to each other, until no such pair is left. Print the result, or print empty if nothing is left.

Constraints

  • 1 <= length <= 10^5

Examples

Input

abbaca

Output

ca

Solutions

Best approachTime O(n)Space O(n)

Removing a pair can create a new pair (abba). A stack handles this in one pass because the new neighbour of a removed pair is the next top of the stack.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process text.
 * Input   : One line of text.
 * Output  : The reduced text.
 * Approach: Use a stack.
 * Time    : O(n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String solve(String s) {
        // Step 1: A StringBuilder works like a stack. Its end is the top of the stack.
        StringBuilder stack = new StringBuilder();

        for (int i = 0; i < s.length(); i++) {
            char letter = s.charAt(i);

            // Step 2: If the top letter equals the new letter, they cancel each other. Remove the top.
            if (stack.length() > 0 && stack.charAt(stack.length() - 1) == letter) {
                stack.deleteCharAt(stack.length() - 1);
            } else {
                // Step 3: Otherwise keep the new letter.
                stack.append(letter);
            }
        }
        return stack.length() == 0 ? "empty" : stack.toString();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.hasNextLine() ? scanner.nextLine() : "";
        System.out.println(solve(s));
    }
}
Hints (1)
  1. Which letter does a new letter meet first?