Taro Logo

Remove All Adjacent Duplicates in String II

#4 Most AskedMedium
0 views
Topics:
StringsStacks

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.

Example 2:

Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation: 
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"

Example 3:

Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"

Constraints:

  • 1 <= s.length <= 105
  • 2 <= k <= 104
  • s only contains lowercase English letters.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the character set of the input string s? For example, should we expect only lowercase English letters, or could it include uppercase letters, numbers, or special characters?
  2. What are the constraints on the length of the string s and the integer k?
  3. How should we handle an empty string s or a value of k that is less than 2?
  4. If multiple k-duplicate removals are possible at the same time, does the order of removal matter, or will it always result in the same final string?
  5. Should we modify the input string in-place if possible, or is returning a new string expected?

Brute Force Solution

Approach

Imagine you have a long text where certain matching letters repeat right next to each other a specific number of times and you want to completely clear them out. The brute force strategy involves scanning the entire text from start to finish, looking for any group of matching letters that meets the target count, and then erasing them on the spot.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very beginning of the text.
  2. Check if the required number of identical letters are sitting right next to each other.
  3. If you find such a group, remove those specific letters from the text completely.
  4. Because removing those letters might cause new matching letters to crash into each other and form a new group, you must go back to the very beginning of the newly shortened text.
  5. Repeat the entire process of scanning and removing from the start.
  6. Keep repeating this search and removal cycle until you can read through the entire text from beginning to end without finding a single group of matching letters that reaches the target count.
  7. Stop and accept whatever is left of the text as your final answer once no more matching groups can be found anywhere.

Code Implementation

def remove_duplicates(input_string, target_count):
    working_string = input_string
    
    # We track whether changes occurred to know if we need to rescan from the beginning
    has_mutation_occurred = True
    
    while has_mutation_occurred:
        has_mutation_occurred = False
        string_length = len(working_string)
        current_index = 0
        
        while current_index < string_length:
            character_to_match = working_string[current_index]
            run_length = 0
            
            while current_index + run_length < string_length and working_string[current_index + run_length] == character_to_match:
                run_length += 1
                
            # If we find a matching run meeting the target count, we must remove it immediately
            if run_length >= target_count:
                working_string = working_string[:current_index] + working_string[current_index + target_count:]
                has_mutation_occurred = True
                
                # Restart scan from the beginning because the removal might have formed new adjacent duplicates
                break
                
            current_index += run_length
            
    return working_string

Big(O) Analysis

Time Complexity
O(n²) – In this brute force strategy, we repeatedly scan the text of length n from the beginning to find and remove adjacent duplicates of size k. Each time a removal occurs, we must restart our scan from the very beginning of the shortened text, potentially taking up to n passes in the worst-case scenario. Within each pass, examining and shifting elements across the remaining string takes up to n operations. This leads to approximately n * n/2 operations, which simplifies to O(n²).
Space Complexity
O(N) – To implement the strategy of gathering items and keeping track of how many times they repeat consecutively, we use an auxiliary stack data structure alongside a string builder. In the worst-case scenario where no adjacent duplicates are removed, this stack and the resulting string must store all N characters from the input. As the input size N grows, the memory consumed by these tracking structures scales proportionally, leading to a linear auxiliary space complexity.

Optimal Solution

Approach

The optimal approach uses a mental stacking technique to build the final text piece by piece. As you examine each character, you keep track of how many times it has appeared in a row, allowing you to instantly clear away groups that reach the forbidden limit before moving forward.

Here's how the algorithm would work step-by-step:

  1. Imagine building the final result on a tray by placing incoming characters one by one from left to right.
  2. Keep a running count alongside your tray to remember how many times the most recent character has repeated consecutively.
  3. Whenever you place a new character, check if it matches the previous one; if it does, increase its streak count, and if it does not, reset the streak count to one for this new character.
  4. Whenever a character's streak count reaches the target limit, immediately remove that entire group of characters from your tray.
  5. After removing a group, update your streak count to match whatever character is now exposed at the end of the tray.
  6. Continue this process for every character in the original text, letting the tray naturally absorb and clean up matching sequences.
  7. Once you have processed everything, whatever remains on the tray represents your final answer.

Code Implementation

def remove_duplicates(input_string, target_limit):
    result_tray = []
    streak_counts = []

    for current_character in input_string:
        # We maintain parallel stacks to track character identity and its current consecutive streak.
        if result_tray and result_tray[-1] == current_character:
            result_tray.append(current_character)
            streak_counts.append(streak_counts[-1] + 1)
        else:
            result_tray.append(current_character)
            streak_counts.append(1)

        # Instantly eliminate the group once it hits the forbidden limit to prevent valid sub-chains.
        if streak_counts[-1] == target_limit:
            for removal_index in range(target_limit):
                result_tray.pop()
                streak_counts.pop()

    # Combining remaining tray elements yields the cleaned result.
    return "".join(result_tray)

Big(O) Analysis

Time Complexity
O(n) – To analyze the time complexity, let n be the length of the input string. We iterate through each character of the string exactly once, performing constant time operations like checking and updating the stack of characters and their consecutive counts. Each character is pushed onto and popped from the stack at most once, meaning no character is processed more than a few times. Summing up these constant-time steps across all n characters yields approximately n operations. Therefore, the overall time complexity simplifies to O(n).
Space Complexity
O(N) – The auxiliary space is driven by the stack-based tray and its associated streak count tracking, which must hold characters and their consecutive frequencies as we process the input string of size N. In the worst-case scenario where no adjacent duplicates reach the limit k to be removed, every single character and its count are pushed onto the stack, resulting in data structures that grow linearly with the input length. Therefore, the extra memory required scales directly proportional to N, simplifying to Big O of N notation.

Edge Cases

String length is less than k
How to Handle:
The stack will never reach a count of k, so the original string is returned unchanged.
String is empty or null
How to Handle:
An empty or null check at the beginning of the function returns an empty string immediately.
String consists entirely of identical characters whose length is a multiple of k
How to Handle:
The stack count will repeatedly hit k and pop all elements, resulting in a completely empty string.
k equals 1
How to Handle:
Every character is immediately treated as a k-duplicate and popped, resulting in an empty string.
Cascading removals where removing one set of k characters forms a new k-duplicate
How to Handle:
Using a stack allows adjacent elements from previously separated parts of the string to meet and form new k-duplicates naturally.
Extremely large strings up to the maximum constraints
How to Handle:
Using a linear scan with a stack ensures an efficient O(n) time and space complexity without stack overflow.
No adjacent duplicates of length k exist in the string
How to Handle:
Characters are simply pushed onto the stack with their counts reset or incremented, leaving the string unchanged after assembly.
Interleaved duplicate patterns like abba when k is 2
How to Handle:
The stack correctly tracks contiguous groups independently so non-matching characters do not disrupt outer counts.
0/6 completed