Leetcode 1957: Delete Characters to Make Fancy String

grid47
grid47
Exploring patterns and algorithms
Apr 25, 2024 5 min read

Given a string s, you need to remove the minimum possible number of characters to ensure that no character appears three or more times consecutively in the resulting string. The output should be the final string after all necessary deletions.
Problem
Approach
Steps
Complexity
Input: You are given a string s consisting of lowercase English letters.
Example: s = "aaabbccaaa"
Constraints:
• 1 <= s.length <= 10^5
• s consists only of lowercase English letters.
Output: Return the final string after removing the minimum possible characters so that no character appears three or more times consecutively.
Example: Output: "aabbcca"
Constraints:
• The answer is guaranteed to be unique.
Goal: The goal is to remove characters in such a way that no character appears consecutively more than twice.
Steps:
• Step 1: Start iterating through the string from the third character onward.
• Step 2: Keep track of the previous two characters, and ensure that the current character does not match both.
• Step 3: If the current character matches both of the previous two characters, skip it (i.e., remove it). Otherwise, add it to the result.
Goal: The string s will be between 1 and 10^5 characters in length, inclusive, and will only contain lowercase English letters.
Steps:
• 1 <= s.length <= 10^5
• s consists only of lowercase English letters.
Assumptions:
• The string will contain only lowercase English letters.
• The string may contain consecutive identical characters, which could require deletions.
Input: Input: s = "aaabbccaaa"
Explanation: In this example, we start with the string "aaabbccaaa". We remove the third 'a' to get "aabbccaaa", then remove the third 'a' again to get "aabbcca". The output is "aabbcca".

Input: Input: s = "abcde"
Explanation: Since no character appears three times consecutively, the string remains unchanged and the output is "abcde".

Link to LeetCode Lab


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