Problem: 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:
Input: s = "abcd", k = 2 Output: "abcd" Explanation: There's nothing to delete.
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"
Approach: This problem is same as the problem Remove All Adjacent Duplicates In String. If you look closely in the previous problem k is always 2. We will use stack to solve this problem too. Here we won't just push the character but also we need to maintain the current continuous count of the character so if we see the character at the top is same as the current character, we increase its count and if we see the count is same as k then we pop that means we need to push a pair of character and it's count in stack. If the characters are not same then we safely push the pair of current character and 1(current count).
We can solve it without using stack to like we did before however I don't see much of benefit here as we need to maintain a count array anyways so extra storage will be there. I have given this implementation too.
Implementation in C#:
Using Stack:
Without using stack:
Complexity: O(n)
No comments:
Post a Comment