1209. Remove All Adjacent Duplicates in String II

/**

 * 1209. Remove All Adjacent Duplicates in String II

 * You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters

 * from s and removing them, causing the left and the right side of the deleted substring to concatenate together.

 *

 * We repeatedly make k duplicate removals on s until we no longer can.

 * Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.

 * Example 1:

 * Input: s = “abcd”, k = 2

 * Output: “abcd”

 * Explanation: There’s nothing to delete.

*/

See the solution to the problem on github at: https://github.com/zcoderz/leetcode/blob/main/src/main/java/frequent/medium/RemoveAdjacentDuplicates.java

Observation: The question asks to remove duplicate characters from a string but only when the count of duplicates is greater than k. Can handle this by adding characters top a string, checking whether character is same as previous and incrementing count. If count becomes k, we delete characters from last index – k up to the last index. Otherwise, we add the character to string builder. We use StringBuilder because it provides a nice interface to add and delete characters.

Here is the code:

public String removeDuplicates(String s, int k) {
    StringBuilder builder;
    boolean dupExists = true;
    while (dupExists) {
        int count = 0;
        char prior = 'Z';
        dupExists = false;
        builder = new StringBuilder();
        for (int i =0; i < s.length(); i++) {
            char c = s.charAt(i);
            builder.append(c);
            count = c == prior ? count + 1 : 1;
            if (count == k && c == prior) {
                builder.delete(builder.length() - count, builder.length());
                dupExists = true;
                count = 0;
            }
            prior = c;
        }
        s = builder.toString();
    }
    return s;
}