In-Place Run-Length Encoding of Character Arrays

Hard · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

Given a non-empty array chars where each element is a single printable ASCII character, encode adjacent identical characters using run-length compression and return the resulting character list.

Implement compress(chars):

def compress(chars: list[str]) -> list[str]:

Partition chars from left to right into maximal contiguous stretches of identical characters and encode each stretch in order according to these rules:

  • Emit the stretch's character once as a one-character string.
  • When a stretch contains only 1 character, omit any count after it (never emit "1" for a singleton run).
  • When a stretch contains 2 or more characters, emit every base-10 digit of the stretch length as an individual one-character string immediately after the character (for instance, a stretch of length 14 emits "1" followed by "4").
  • Only neighboring matching characters merge into a stretch; if the same character reappears after a different character, it begins a separate stretch.
  • Character comparison is exact and case-sensitive ("r" and "R" do not merge).

Implementation note: Interviewers commonly ask for an in-place algorithm that overwrites the front of a mutable buffer using O(1) auxiliary variables. While compress(chars) returns a list[str] directly so callers can inspect the output list, structure your logic around an in-place two-pointer pass without mutating the caller's list.

Examples

Example 1

Input: chars = ["m", "m", "m", "m", "n", "p", "p", "p"]
Output: ["m", "4", "n", "p", "3"]

Four "m" characters become "m", "4", the lone "n" stays "n" without a "1", and three "p" characters become "p", "3".

Example 2

Input: chars = ["r", "R", "R", "r", "r", "r"]
Output: ["r", "R", "2", "r", "3"]

Lowercase "r" and uppercase "R" are distinct, and the two stretches of "r" stay separate because "R", "R" sits between them.

Example 3

Input: chars = ["w", "w", "w", "w", "w", "w", "w", "w", "w", "w", "w", "w", "w", "w", "!"]
Output: ["w", "1", "4", "!"]

The leading stretch of 14 "w" characters splits its two-digit count into "1" and "4", followed by the singleton "!".

Constraints

  • 1 <= len(chars) <= 2000
  • Every entry in chars has length 1 and is a printable ASCII character (an uppercase or lowercase English letter, a decimal digit '0'–'9', a space, or punctuation/symbol).

Step-by-step walkthrough

  1. Understand the goal and the stretch rules

    We receive a non-empty list chars of one-character strings and want to encode contiguous runs of identical characters:

    • Every maximal stretch of equal neighboring characters forms one group.
    • If a group has length 1, we emit just the character (never "1" after it).
    • If a group has length 2 or more, we emit the character followed by each decimal digit of the length as its own one-character string.
    Input:   ["r", "R", "R", "r", "r", "r"]   ["w", "w", ..., "w", "!"]  (14 "w"s + "!")
    Groups:   "r" | "RR"    | "rrr"            "wwwwwwwwwwwwww" | "!"
    Output:  ["r", "R", "2", "r", "3"]        ["w", "1", "4", "!"]   (NOT ["w", "14", "!"])
    

    Two rules to keep in mind: only adjacent matches merge (the two "r" stretches in Example 2 stay separate), and character matching is case-sensitive ("r" and "R" are distinct).

  2. Why we build the two-pointer in-place routine

    With len(chars) <= 2000, appending to a brand-new output list would already run in linear time. However, interviewers prize the classic in-place formulation of this task: overwrite the front of a mutable array using only a few integer indices, and return the new compressed length.

    If we write a helper compress_in_place(buffer) that encodes a list over its own front slots, our public compress(chars) function only needs to shallow-copy chars once (so the caller's list stays untouched), run compress_in_place, and slice the valid prefix.

  3. Why overwriting in place never clobbers unread characters

    We maintain two integer indices into buffer:

    • read_idx (the scout): scans forward across a complete group of matching characters.
    • write_idx (the writer): marks the next slot where compressed output goes.

    Could write_idx ever run ahead of read_idx and erase a character we have not read yet? Check how many slots a group of run_length characters consumes when compressed:

    run_length = 1        ->  ["m"]                   (1 slot written for 1 read)
    run_length = 2 .. 9   ->  ["m", "2"] .. ["m", "9"] (2 slots written for 2..9 read)
    run_length = 10 .. 99 ->  ["m", "1", "0"] ...      (3 slots written for 10..99 read)
    run_length = 2000     ->  ["m", "2", "0", "0", "0"] (5 slots written for 2000 read)
    

    A group's encoded form is never longer than the group itself. Because we also advance read_idx to the end of the current group before writing anything for that group, write_idx always stays at or behind read_idx and only touches slots we have already finished reading:

    Before writing group "ppp" at indices 5..7 (write_idx = 3, group_start = 5):
      index:   0    1    2    3    4    5    6    7
      buffer: ["m", "4", "n", "m", "n", "p", "p", "p"]
                                   ^              ^
                               write_idx          |  read_idx = 8 (past end)
                                        group_start = 5
    Writes land at indices 3 and 4 ("p", "3") — both strictly below read_idx (8).
    
  4. Phase 1: Scan one maximal run of identical neighbors

    At the start of each outer loop iteration, read_idx sits on the first character of a new group. We save that character in group_char and its starting index in group_start, then advance read_idx as long as the character matches:

    def scan_one_group_demo(buffer: list[str], read_idx: int) -> tuple[str, int, int]:
        total_chars = len(buffer)
        # Save group_char now because read_idx will advance to the next group (or total_chars).
        group_char = buffer[read_idx]
        group_start = read_idx
        while read_idx < total_chars and buffer[read_idx] == group_char:
            read_idx += 1
        run_length = read_idx - group_start
        return group_char, run_length, read_idx
    

    Saving group_char before the inner while loop is essential: when the inner loop stops, read_idx either equals total_chars (out of bounds) or points at the first character of the next group.

  5. Phase 2: Write the character and multi-digit count

    Once group_char and run_length are known, we write group_char at buffer[write_idx] and advance write_idx. Only when run_length > 1 do we convert run_length to its decimal string str(run_length) and write each digit character one slot at a time ("1" then "4" for 14):

    def compress_in_place(buffer: list[str]) -> int:
        """Overwrite the front of `buffer` with its run-length encoding and return the new length."""
        total_chars = len(buffer)
        read_idx = 0
        write_idx = 0
    
        while read_idx < total_chars:
            group_char = buffer[read_idx]
            group_start = read_idx
            while read_idx < total_chars and buffer[read_idx] == group_char:
                read_idx += 1
            run_length = read_idx - group_start
    
            buffer[write_idx] = group_char
            write_idx += 1
    
            if run_length > 1:
                for digit_char in str(run_length):
                    buffer[write_idx] = digit_char
                    write_idx += 1
    
        return write_idx
    

    When read_idx reaches total_chars, write_idx equals the exact number of elements written, so buffer[:write_idx] is the compressed list.

  6. Trace Example 1 and Example 3 step by step

    Let's trace Example 1 on buffer = ["m", "m", "m", "m", "n", "p", "p", "p"]:

    Start:  buffer = [m, m, m, m, n, p, p, p],  read_idx = 0, write_idx = 0
    
    Group 1: group_char = "m", group_start = 0 -> read_idx stops at 4 -> run_length = 4
             Write "m" at [0], "4" at [1] -> write_idx = 2
             buffer = [m, 4, m, m, n, p, p, p]
    
    Group 2: group_char = "n", group_start = 4 -> read_idx stops at 5 -> run_length = 1
             Write "n" at [2] (skip count since run_length == 1) -> write_idx = 3
             buffer = [m, 4, n, m, n, p, p, p]
    
    Group 3: group_char = "p", group_start = 5 -> read_idx stops at 8 -> run_length = 3
             Write "p" at [3], "3" at [4] -> write_idx = 5
             buffer = [m, 4, n, p, 3, p, p, p]
    
    Slice buffer[:5] -> ["m", "4", "n", "p", "3"]
    

    In Example 3 (14 copies of "w" followed by "!"), Group 1 scans group_start = 0 through read_idx = 14 (run_length = 14) and writes "w", "1", "4" at indices 0..2; Group 2 scans "!" at index 14 (run_length = 1) and writes "!" at index 3, returning buffer[:4] == ["w", "1", "4", "!"].

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def compress_in_place(buffer: list[str]) -> int:
        """Overwrite the front of `buffer` with its run-length encoding and return the new length."""
        total_chars = len(buffer)
        # read_idx: fast pointer scanning the start and end of each contiguous character run
        read_idx = 0
        # write_idx: slow pointer marking the next slot in `buffer` to receive compressed output
        write_idx = 0
    
        while read_idx < total_chars:
            # Phase 1: Measure the full run of identical adjacent characters starting at read_idx.
            # Save group_char now because read_idx will advance to the next group (or total_chars).
            group_char = buffer[read_idx]
            group_start = read_idx
            while read_idx < total_chars and buffer[read_idx] == group_char:
                read_idx += 1
            run_length = read_idx - group_start
    
            # Phase 2: Write the character once, followed by each decimal digit if run_length > 1.
            # Invariant: write_idx <= group_start, and 1 + digits(run_length) <= run_length for all
            # run_length >= 2, so write_idx never overtakes read_idx or overwrites unread elements.
            buffer[write_idx] = group_char
            write_idx += 1
    
            # Runs of length 1 omit the count "1" by rule; only runs of 2 or more write digits.
            if run_length > 1:
                for digit_char in str(run_length):
                    buffer[write_idx] = digit_char
                    write_idx += 1
    
        return write_idx
    
    
    def compress(chars: list[str]) -> list[str]:
        # Work on a shallow copy so we do not mutate the caller's input list.
        buffer = list(chars)
        compressed_length = compress_in_place(buffer)
        return buffer[:compressed_length]
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture two coworkers walking left to right down a single row of letter tiles: a scout (read_idx) walks ahead to count how many matching tiles sit side by side, and a painter (write_idx) follows behind, painting the character and the digits of its count onto tiles the scout has already inspected. Replacing consecutive repeats of a symbol with one copy of the symbol plus its repeat count is called run-length encoding (RLE), and updating the list over its own front slots with a fast reader and a slow writer is called in-place two-pointer compression (modifying an existing array using two moving indices instead of allocating a separate output buffer). Because any run of length 1 becomes 1 tile ("n"), any run of length 2..9 becomes 2 tiles ("p", "3"), and any run of 10 or more becomes 1 + digits tiles (3 tiles for 14, 5 tiles for 2000), the compressed form is never longer than the run itself — so the painter can never catch up to or overwrite tiles the scout hasn't read yet.

Why do the obvious beginner attempts go wrong? Counting total character frequencies with a dictionary or Counter merges non-adjacent groups, turning ["r", "R", "R", "r", "r", "r"] into ["r", "4", "R", "2"] instead of keeping the separated "r" stretches distinct as ["r", "R", "2", "r", "3"]. Appending str(run_length) directly as a single element produces "14" instead of splitting multi-digit counts into "1" and "4", or accidentally appends "1" after single characters. Finally, comparing chars[i] with chars[i + 1] in a single loop often drops the final run at the end of the list unless duplicate cleanup code is added after the loop, whereas a nested group-scanning loop handles every group uniformly.

Let's trace Example 1 (chars = ["m", "m", "m", "m", "n", "p", "p", "p"]) step by step:

Initial copy:  buffer = ["m", "m", "m", "m", "n", "p", "p", "p"],  read_idx = 0, write_idx = 0

1. Scout reads "m" from index 0 to 4 -> run_length = 4.
   Painter writes "m", "4" at indices 0..1 -> write_idx = 2.
   buffer = ["m", "4", "m", "m", "n", "p", "p", "p"]

2. Scout reads "n" from index 4 to 5 -> run_length = 1.
   Painter writes "n" at index 2 (no "1" for length 1) -> write_idx = 3.
   buffer = ["m", "4", "n", "m", "n", "p", "p", "p"]

3. Scout reads "p" from index 5 to 8 -> run_length = 3.
   Painter writes "p", "3" at indices 3..4 -> write_idx = 5.
   buffer = ["m", "4", "n", "p", "3", "p", "p", "p"]

Return buffer[:5] -> ["m", "4", "n", "p", "3"]

Complexity

Let n be len(chars).

  • Time: O(n). Even though there is a while loop inside a while loop, read_idx strictly increases by 1 on every inner step and never moves backward, so each of the n input characters is inspected once; write_idx advances at most n times because the encoded output never exceeds n elements.
  • Space: O(1) auxiliary space inside compress_in_place (O(n) total in compress). The in-place worker uses only a handful of integer indices plus str(run_length), which holds at most 4 digit characters for n <= 2000 (O(log n) digits in general); compress allocates one O(n) copy list(chars) so it can return the compressed list without mutating the caller's input.

Edge cases

  • Single-element list (["a"]): Forms one run of length 1, returning ["a"] with no "1" appended.
  • No two equal neighbors (["a", "b", "c", "a"]): Every run has length 1, so the output equals the input (write_idx stays equal to read_idx after every group).
  • Single-digit to two-digit boundary (9 vs 10): ["a"] * 9 writes ["a", "9"] (2 elements), while ["b"] * 10 writes ["b", "1", "0"] (3 elements).
  • Maximum constraint run (["q"] * 2000): Produces 5 elements ["q", "2", "0", "0", "0"], including trailing "0" characters.
  • Separated runs of the same character (["r", "R", "R", "r", "r", "r"]): Each contiguous stretch is compressed independently into ["r", "R", "2", "r", "3"].
  • Case sensitivity (["a", "A", "A", "a"]): Lowercase "a" and uppercase "A" do not match, producing ["a", "A", "2", "a"].
  • Digit and symbol characters in the input (["1", "1", "1", "2"]): Treated like any other character, producing ["1", "3", "2"].

Common mistakes

  • Appending multi-digit counts as one string: Writing buffer[write_idx] = str(run_length) puts "14" into a single list slot instead of "1" followed by "4".
  • Writing "1" after single characters: Using if run_length >= 1: instead of if run_length > 1: turns ["n"] into ["n", "1"], which violates the singleton rule AND makes the output longer than the input (breaking in-place safety!).
  • Reading buffer[read_idx] after the inner loop: Once the inner while loop ends, read_idx points at the start of the next run (or equals len(buffer)), so you must save group_char = buffer[read_idx] before advancing read_idx.
  • Returning buffer without slicing buffer[:compressed_length]: Leftover characters from the tail of the original buffer remain at indices >= compressed_length and must be sliced off.

Alternative approaches

  • Strict O(1) digit extraction without str(run_length): If interview rules forbid even the tiny str(run_length) string allocation, extract digits in reverse order using run_length % 10 and run_length //= 10, write chr(ord("0") + digit) starting at digit_start = write_idx, and then reverse the sub-slice buffer[digit_start:write_idx] in place with two indices.

Follow-up questions

  • Why can the compressed result never exceed the length of the input array, and how does that guarantee make in-place overwriting safe? A singleton run (k = 1) writes 1 character (1 <= 1), a pair (k = 2) writes 2 characters (2 <= 2), and every longer run (k >= 3) writes 1 + (floor(log10(k)) + 1) characters, which is strictly smaller than k (for example, 3 slots for k = 10). Because omitting "1" prevents singleton runs from expanding, write_idx never advances farther than the number of elements already scanned by read_idx, guaranteeing we never overwrite unread characters.
  • When the input array may contain digit characters like '0'–'9', is the compressed output uniquely decodable, and how would you modify the format if lossless decoding were required? No — when raw digits can appear in chars, decoding is ambiguous: both ["1", "1"] (two "1"s) and ["1", "2"] (one "1" followed by one "2") encode to ["1", "2"]. Lossless decoding over arbitrary ASCII requires framing each run unambiguously, such as prefixing every run with a delimiter-terminated count ("2#1" vs "1#1", "1#2") or escaping literal digits, at the cost of allowing short inputs to expand beyond len(chars).
  • How would you adapt this algorithm to compress an unbounded character stream that cannot fit in RAM? Keep only two scalar state variables — active_char and active_count — while reading chunks sequentially from the input stream. Whenever an incoming character differs from active_char, flush active_char (plus the base-10 digits of active_count if active_count > 1) to the output stream and reset (active_char, active_count) = (ch, 1), flushing the final active run at end-of-stream in O(1) memory.

Follow-up questions

Similar questions

More Abridge interview questions

All 4 Abridge questions →