Remove runs of length at least k
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates string manipulation, run-length detection, and algorithmic efficiency, focusing on tracking and removing maximal contiguous character groups. It is commonly asked in the Coding & Algorithms domain to assess practical application–level skills in designing linear-time, linear-space implementations that handle dynamic sequence collapses using appropriate data structures.
Constraints
- 0 <= len(s) <= 10^5
- s consists of lowercase English letters
- 2 <= k <= len(s) (when len(s) >= 2); for very short strings k may exceed len(s), in which case nothing is removed
- Return the empty string if everything is removed
Examples
Input: ('abbbbc', 3)
Expected Output: 'ac'
Explanation: The single run 'bbbb' has length 4 >= 3, so the whole group is removed, leaving 'a' + 'c' = 'ac'.
Input: ('aaabbbcc', 3)
Expected Output: 'cc'
Explanation: 'aaa' (len 3) and 'bbb' (len 3) are both removed; 'cc' (len 2 < 3) remains.
Hints
- First reduce the input to a list of runs: consecutive (character, count) pairs. A run is removable iff count >= k.
- The hard part is the cascade: after you delete a run, the run to its left and the run to its right become adjacent. If they are the same character, they merge into one larger run whose new length might now be >= k, triggering another deletion — which can chain further left or right.
- A correct-and-simple model is to repeatedly scan the string, dropping every maximal run with length >= k, and rebuild until a full pass makes no change. This is easy to reason about and matches the definition exactly.
- For O(n): use a stack of (char, count). For each incoming character, increment the top's count if it matches, else push (char, 1). When a top's count reaches k, pop it; then if the new top's character equals the next character you append, they merge — re-check the merged count against k to cascade. Be careful that a removal can also let the element below merge upward.
- Watch the boundary: removing the entire run means a run of length 5 with k = 3 disappears completely, not down to length 2 (5 - 3). Don't confuse this with 'remove exactly k duplicates'.