Encode Consecutive Character Runs as Digit Sequences
StringsAuto-graded · 19 test casesLast updated
Tests run-length encoding with multi-digit counts split into individual characters, requiring careful pointer management and constant-space thinking.
Given a list chars containing single-character strings, encode it using run-length encoding. Scan left to right and identify each maximal sequence of identical consecutive characters. For each sequence, output the character once, followed by the digits of the sequence length (if greater than 1), with each digit as a separate list element.
Return the encoded result as a list of single-character strings.
Encoding Rules
- A sequence of length 1 is represented by the character alone, with no count digit.
- A sequence of length 10 or greater must have its count split into separate digit characters. For example, a run of 15 becomes the character followed by
"1"then"5". - Only consecutive identical characters form a sequence. If the same character appears later after different characters, it starts a new sequence.
- Character comparison is case-sensitive:
"A"and"a"are distinct.
Constraints
1 <= len(chars) <= 2000- Each element of
charsis a single character (letter, digit, or printable ASCII symbol)
Examples
Example 1
Input: encode_runs(['x', 'x', 'x', 'y', 'z', 'z'])
Output: ['x', '3', 'y', 'z', '2']
Example 2
Input: encode_runs(['a', 'b', 'b', 'a', 'a'])
Output: ['a', 'b', '2', 'a', '2']
Example 3
Input: encode_runs(['k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k'])
Output: ['k', '1', '2']
Hints
Hint 1
Use two pointers: one to mark where each run starts, another to find where it ends by scanning while characters match.
Hint 2
Convert the run length to a string to get its digits, then add each digit individually to the output.
Hint 3
The total output length never exceeds the input length, which is why an in-place solution is possible.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use a two-pointer technique to identify each maximal run of consecutive identical characters. The first pointer i marks the beginning of the current run, while the second pointer j advances from i until it reaches a different character or the end of the list. The distance j - i gives the run length.
For each run, append the character to the result. If the run contains more than one character, convert the count to a string and extend the result with each digit individually. Then move i to j to begin processing the next run.
The key insight is that extend(str(count)) iterates over the string representation and adds each digit as a separate element, which satisfies the requirement that multi-digit counts must be split.
Correctness
- Each run is maximal because
jadvances until it finds a character different fromchars[i], ensuring no run can be extended rightward. - Runs are non-overlapping and cover all elements because
ijumps directly tojafter processing each run. - Runs are detected from left to right, so each new run begins immediately after a character change.
- Characters appearing multiple times in non-adjacent positions form separate runs, as required.
- Single-character runs emit only the character itself, while longer runs emit the character followed by each digit of the count in order.
Complexity
- Time: O(n) where n is the length of the input. Each position is visited exactly once by the advancing pointer
j. Converting counts to digit strings takes O(log₁₀ n) per run, but the total output size bounds this work to O(n). - Space: O(1) auxiliary space beyond the output list. The output never exceeds n elements because each run of length L ≥ 2 produces at most L elements (1 character + at most L-1 digits).
Edge Cases
- Single element:
["q"]returns["q"] - All distinct characters: output equals input
- Runs of exactly 10: produce three elements like
["x", "1", "0"] - Maximum-length runs (2000 characters): produce character plus
"2", "0", "0", "0" - Digit characters as data:
["1", "1", "1"]correctly returns["1", "3"] - Case sensitivity:
["a", "A", "a"]returns["a", "A", "a"](three separate runs) - Final run: handled naturally by the loop condition without special post-processing
def encode_runs(chars: list[str]) -> list[str]:
result = []
n = len(chars)
i = 0
while i < n:
j = i
while j < n and chars[j] == chars[i]:
j += 1
result.append(chars[i])
if j - i > 1:
result.extend(str(j - i))
i = j
return result