Construct String With Repeat Limit - Problem

You are given a string s and an integer repeatLimit. Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row.

You do not have to use all characters from s.

Return the lexicographically largest repeatLimitedString possible.

A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.

Input & Output

Example 1 — Basic Case
$ Input: s = "cczazcc", repeatLimit = 3
Output: "zzcccacc"
💡 Note: Start with largest character 'z' (appears 2 times), then 'c' (3 times max), then use 'a' as separator, then remaining 'c'.
Example 2 — Repeat Limit Hit
$ Input: s = "aababab", repeatLimit = 2
Output: "bbabaa"
💡 Note: Use 'b' twice, then 'a' as separator, then 'b' once, then remaining 'a' characters.
Example 3 — Single Character Type
$ Input: s = "aaaa", repeatLimit = 2
Output: "aa"
💡 Note: Only one character type available, use up to repeat limit and stop (no separator available).

Constraints

  • 1 ≤ s.length ≤ 105
  • 1 ≤ repeatLimit ≤ 104
  • s consists of lowercase English letters.

Visualization

Tap to expand
Construct String With Repeat Limit INPUT String s = "cczazcc" c c z a z c c Character Frequency: z: 2 (highest) c: 4 a: 1 (lowest) repeatLimit = 3 Max consecutive same chars Goal: Build lexicographically LARGEST string possible with repeat constraint ALGORITHM (Greedy) 1 Count Characters Store frequency of each char 2 Pick Largest Available Start with 'z' (highest) 3 Apply Repeat Limit Add up to 3 of same char 4 Insert Breaker Char Use next largest to break Building Process: "" --> "zz" (add 2 z's) "zz" --> "zzccc" (add 3 c's) "zzccc" --> "zzccca" (break!) "zzccca" --> "zzcccacc" (add c's) Repeat until no chars left FINAL RESULT Output: "zzcccacc" z z c c c a c c Highest char (z) Breaker char (a) Verification: [OK] Max 3 consecutive chars [OK] Lexicographically largest [OK] All chars used from s Analysis: 'a' breaks the 'c' sequence allowing more c's after it "zz" + "ccc" + "a" + "cc" Key Insight: The greedy approach always picks the lexicographically largest available character. When the repeat limit is reached, we insert ONE character of the next largest available char as a "breaker", then continue with the original largest. This ensures the result is lexicographically maximum while respecting the limit. TutorialsPoint - Construct String With Repeat Limit | Greedy Approach
Asked in
Google 28 Amazon 23 Facebook 15 Microsoft 12
23.4K Views
Medium-High Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen