Leetcode 2182: Construct String With Repeat Limit

grid47
grid47
Exploring patterns and algorithms
Apr 2, 2024 6 min read

Given a string of lowercase letters and an integer limit, construct a new string such that no character appears more than the given limit times consecutively. The new string should be lexicographically largest while satisfying this condition. You can use any subset of characters from the given string.
Problem
Approach
Steps
Complexity
Input: A string of lowercase English letters and an integer repeatLimit.
Example: Input: s = 'bbaaccd', repeatLimit = 2
Constraints:
• 1 <= repeatLimit <= s.length <= 10^5
• s consists of only lowercase English letters.
Output: A lexicographically largest string satisfying the condition that no character appears more than repeatLimit times consecutively.
Example: Output: 'ccbbaa'
Constraints:
• No character appears consecutively more than repeatLimit times.
• Characters are used from the input string.
Goal: Construct the lexicographically largest string that satisfies the repeatLimit constraint.
Steps:
• Count the frequency of each character in the string.
• Use a max-heap to process characters by their lexicographical order and frequency.
• Construct the result string by adding characters within the repeatLimit constraint.
• Handle cases where the highest frequency character cannot continue by inserting the next highest character.
Goal: Conditions that the solution must satisfy.
Steps:
• 1 <= repeatLimit <= s.length <= 10^5
• The input string consists of only lowercase English letters.
Assumptions:
• Input string is not empty.
• repeatLimit is at least 1.
Input: Input: s = 'abcabc', repeatLimit = 2
Explanation: The result is 'ccbbaa'. Each character appears at most twice consecutively, and the string is lexicographically largest.

Input: Input: s = 'xyzxxy', repeatLimit = 3
Explanation: The result is 'yyxxyz'. The character 'y' appears 2 times consecutively, while 'x' and 'z' appear at most 2 times.

Link to LeetCode Lab


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