KatInterview

Encode Consecutive Character Runs as Digit Sequences

StringsAuto-graded · 19 test cases
HardAuto-gradedStringstwo-pointersrun-length-encodingin-place

Last 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 chars is 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.