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
14emits"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
charshas length1and 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
Understand the goal and the stretch rules
We receive a non-empty list
charsof 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
2or 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).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 publiccompress(chars)function only needs to shallow-copycharsonce (so the caller's list stays untouched), runcompress_in_place, and slice the valid prefix.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_idxever run ahead ofread_idxand erase a character we have not read yet? Check how many slots a group ofrun_lengthcharacters 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_idxto the end of the current group before writing anything for that group,write_idxalways stays at or behindread_idxand 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).Phase 1: Scan one maximal run of identical neighbors
At the start of each outer loop iteration,
read_idxsits on the first character of a new group. We save that character ingroup_charand its starting index ingroup_start, then advanceread_idxas 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_idxSaving
group_charbefore the innerwhileloop is essential: when the inner loop stops,read_idxeither equalstotal_chars(out of bounds) or points at the first character of the next group.Phase 2: Write the character and multi-digit count
Once
group_charandrun_lengthare known, we writegroup_charatbuffer[write_idx]and advancewrite_idx. Only whenrun_length > 1do we convertrun_lengthto its decimal stringstr(run_length)and write each digit character one slot at a time ("1"then"4"for14):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_idxWhen
read_idxreachestotal_chars,write_idxequals the exact number of elements written, sobuffer[:write_idx]is the compressed list.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 (
14copies of"w"followed by"!"), Group 1 scansgroup_start = 0throughread_idx = 14(run_length = 14) and writes"w","1","4"at indices0..2; Group 2 scans"!"at index14(run_length = 1) and writes"!"at index3, returningbuffer[:4] == ["w", "1", "4", "!"].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 awhileloop inside awhileloop,read_idxstrictly increases by1on every inner step and never moves backward, so each of theninput characters is inspected once;write_idxadvances at mostntimes because the encoded output never exceedsnelements. - Space:
O(1)auxiliary space insidecompress_in_place(O(n)total incompress). The in-place worker uses only a handful of integer indices plusstr(run_length), which holds at most4digit characters forn <= 2000(O(log n)digits in general);compressallocates oneO(n)copylist(chars)so it can return the compressed list without mutating the caller's input.
Edge cases
- Single-element list (
["a"]): Forms one run of length1, returning["a"]with no"1"appended. - No two equal neighbors (
["a", "b", "c", "a"]): Every run has length1, so the output equals the input (write_idxstays equal toread_idxafter every group). - Single-digit to two-digit boundary (
9vs10):["a"] * 9writes["a", "9"](2 elements), while["b"] * 10writes["b", "1", "0"](3 elements). - Maximum constraint run (
["q"] * 2000): Produces5elements["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: Usingif run_length >= 1:instead ofif 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 innerwhileloop ends,read_idxpoints at the start of the next run (or equalslen(buffer)), so you must savegroup_char = buffer[read_idx]before advancingread_idx. - Returning
bufferwithout slicingbuffer[:compressed_length]: Leftover characters from the tail of the original buffer remain at indices>= compressed_lengthand must be sliced off.
Alternative approaches
- Strict
O(1)digit extraction withoutstr(run_length): If interview rules forbid even the tinystr(run_length)string allocation, extract digits in reverse order usingrun_length % 10andrun_length //= 10, writechr(ord("0") + digit)starting atdigit_start = write_idx, and then reverse the sub-slicebuffer[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) writes1character (1 <= 1), a pair (k = 2) writes2characters (2 <= 2), and every longer run (k >= 3) writes1 + (floor(log10(k)) + 1)characters, which is strictly smaller thank(for example,3slots fork = 10). Because omitting"1"prevents singleton runs from expanding,write_idxnever advances farther than the number of elements already scanned byread_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 beyondlen(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_charandactive_count— while reading chunks sequentially from the input stream. Whenever an incoming character differs fromactive_char, flushactive_char(plus the base-10 digits ofactive_countifactive_count > 1) to the output stream and reset(active_char, active_count) = (ch, 1), flushing the final active run at end-of-stream inO(1)memory.
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?
- 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?
- How would you adapt this algorithm to compress an unbounded character stream that cannot fit in RAM?
Similar questions
- Nested Bracket-Count String Decoder
- Sum of 3, 5, and 7 Multiples Within [1, n]
- HIPAA-Compliant Clinical Audio Transcription Pipeline
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses