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 <= 1052 <= k <= 104s only contains lowercase English letters.This approach utilizes a stack data structure to track characters and their counts. As we iterate through the string, we push characters with their current counts on the stack. When the count of the top character in the stack reaches k, we pop the character from the stack to simulate removal of duplicates.
The C solution uses a dynamic character array res to construct the result string, simulating a stack. An auxiliary array count keeps track of the current streak of consecutive characters. When the count reaches k, the top character is removed.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), for the stack and auxiliary storage.
This approach utilizes a two-pointer technique to modify the string in place. Here, we treat the string as a character array, using one pointer to scan the input and another to build the output string. A helper array is used to store counts of consecutive characters.
The C solution employs an extra integer array to keep track of the count of consecutive characters for each position j in the resultant array. Characters are removed in-place by adjusting the index j accordingly.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(n)
| Approach | Complexity |
|---|---|
| Stack-Based Solution | Time Complexity: O(n), where n is the length of the string. |
| In-Place Two-Pointer Technique | Time Complexity: O(n) |
Remove All Adjacent Duplicates in String II - Leetcode 1209 - Python • NeetCode • 53,400 views views
Watch 9 more video solutions →Practice Remove All Adjacent Duplicates in String II with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor