Leetcode 1209: Remove All Adjacent Duplicates in String II

grid47
grid47
Exploring patterns and algorithms
Jul 9, 2024 5 min read

You are given a string s and an integer k. A k duplicate removal consists of selecting k adjacent and equal letters from the string and removing them, causing the left and the right side of the deleted substring to concatenate together. Repeat this operation until no more such removals are possible. Return the final string after all removals are done.
Problem
Approach
Steps
Complexity
Input: You are given a string s and an integer k.
Example: Input: s = "aabbcc", k = 2
Constraints:
• 1 <= s.length <= 10^5
• 2 <= k <= 10^4
• s consists of lowercase English letters only.
Output: Return the final string after all k duplicate removals have been made.
Example: Output: ""
Constraints:
Goal: The goal is to continuously remove adjacent duplicate letters from the string until no more removals can be made.
Steps:
• Iterate through the string and check for k adjacent equal letters.
• Whenever such a substring is found, remove it and concatenate the remaining parts of the string.
• Repeat this process until no more substrings can be removed.
Goal: The input string s is guaranteed to contain only lowercase English letters and to meet the specified length and k values.
Steps:
• 1 <= s.length <= 10^5
• 2 <= k <= 10^4
• s only contains lowercase English letters.
Assumptions:
• The string s may contain substrings with duplicate characters that need to be removed.
• The solution should handle cases where there are no substrings to remove, as well as when all characters can be removed.
Input: Input: s = "aabbcc", k = 2
Explanation: Since the string contains only pairs of identical characters, all of them will be removed, leaving the string empty.

Input: Input: s = "aaaabbbcccddeee", k = 3
Explanation: After removing 'aaa', 'bbb', 'ccc', and 'ddd', the string reduces to 'ddee'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus