Run-Length String Encoding With Length Fallback
Medium · Coding & Algorithms · Backend Engineer · Onsite
Problem Statement
Implement compress(s) to apply run-length encoding across contiguous streaks of identical letters in s, returning the encoded string only when it uses strictly fewer characters than s (and returning s unchanged otherwise).
Follow these exact encoding rules:
- Maximal contiguous streaks: Partition
sfrom left to right into maximal blocks of consecutive matching characters, and encode every block as<letter><count>where<count>is the block's length in standard base-10 digits. - Explicit unit counts: Single-character blocks still include
1(for instance,'p'encodes as"p1"), and separate blocks of the same letter later in the string are encoded independently rather than combined. - Case sensitivity: Uppercase and lowercase versions of a letter are distinct (
'K'and'k'form two separate blocks). - Multi-digit counts: Blocks of
10or more characters write out every decimal digit (12consecutive'K'characters encode as"K12"). - Whole-string strict length check: Evaluate the final encoded length only after processing all of
s. Return the encoded string iflen(encoded) < len(s); wheneverlen(encoded) >= len(s), returnsas-is (so""returns"").
def compress(s: str) -> str:
Examples
Example 1
Input: s = "mmmpqqqqqmm"
Output: "m3p1q5m2"
The four maximal streaks are "mmm", "p", "qqqqq", and "mm", producing "m3p1q5m2" (8 characters versus the input's 11 characters).
Example 2
Input: s = "xxxyzz"
Output: "xxxyzz"
Encoding produces "x3y1z2", which has 6 characters—tied with len("xxxyzz") == 6. Because 6 is not strictly less than 6, the original string "xxxyzz" is returned.
Example 3
Input: s = "KKKKKKKKKKKKk"
Output: "K12k1"
Twelve uppercase 'K' characters encode as "K12" and the trailing lowercase 'k' encodes separately as "k1", shrinking 13 characters down to 5.
Constraints
0 <= len(s) <= 10^5sconsists solely of ASCII English letters ('a'–'z'and'A'–'Z').
Step-by-step walkthrough
Understand when run-length encoding actually shrinks a string
Given a string
sof up to100,000ASCII letters (a–z,A–Z), we replace every run (maximal contiguous streak of identical characters) with<character><decimal_count>:s = "mmm" + "p" + "qqqqq" + "mm" (length 11) encoded = "m3" + "p1" + "q5" + "m2" (length 8 < 11 -> keep encoded!)Notice how streak length determines space savings: - A streak of
1("p" -> "p1") expands from 1 character to 2. - A streak of2("mm" -> "m2") breaks even at 2 characters. - Only streaks of3or longer ("qqqqq" -> "q5") save characters!Four details must hold simultaneously: 1. Case-sensitive comparison:
'K'and'k'never merge into one run ("KKKKKKKKKKKKk"splits into12'K's and1'k'). 2. Every streak emits its count: Even a single'p'becomes"p1", and non-adjacent streaks of'm'stay separate ("mmmpqqqqqmm"emits"m3"at the front and"m2"at the end). 3. Multi-digit decimal counts: Twelve'K's become"K12"(3 characters), writing out all base-10 digits. 4. Strictly shorter wins: Return the encoded string only iflen(compressed) < len(s). Ties ("xxxyzz"vs"x3y1z2") and expansions ("abc"vs"a1b1c1") returnsunchanged.Scan maximal runs cleanly with two pointers
A classic trap when grouping streaks is checking
s[i] != s[i - 1]and emitting only on transitions—which silently drops the final streak at the end ofsunless you duplicate the emit code outside the loop!Using two indices,
run_startandrun_end, eliminates that special case: 1.run_startmarks the opening index of the current streak. 2.run_endbegins atrun_startand steps right whilerun_end < lengthands[run_end] == s[run_start]. 3. Oncerun_endstops, the streak occupiess[run_start : run_end], so its count isrun_end - run_start. 4. Advancerun_start = run_endto land directly on the next streak!Index: 0 1 2 3 4 5 6 7 8 9 10 Chars: m m m p q q q q q m m ^ ^ run_start run_end stops at index 3 ('p' != 'm') -> run_count = 3 - 0 = 3 -> emit 'm', '3', then jump run_start = 3Although one
whileloop sits nested inside anotherwhileloop, total work isO(n)linear time, notO(n^2):run_endadvances monotonically from0tolength, inspecting each index once across the entire function call.Collect pieces in a list to avoid quadratic copying
Python strings are immutable. Appending directly via
compressed += pieceinside a loop can allocate a new string and copy all accumulated characters on every streak, degrading toO(n^2)on alternating strings like"abababab..."with50,000length-1 runs.Instead, append each character and
str(run_count)to a listencoded_parts(O(1)amortized per append), then call"".join(encoded_parts)once at the end to build the output string in a singleO(n)pass.length = len(s) # encoded_parts: flat list of strings alternating [char, decimal_count, ...], e.g. ['a', '2', 'b', '1']. encoded_parts: List[str] = [] # Phase 1: Scan maximal runs [run_start, run_end) of identical characters in one O(n) pass. run_start = 0 while run_start < length: # Advance run_end to the first index past the current run of s[run_start]. run_end = run_start while run_end < length and s[run_end] == s[run_start]: run_end += 1 # Every run (including length 1 and multi-digit counts >= 10) emits char + full decimal count. run_count = run_end - run_start encoded_parts.append(s[run_start]) encoded_parts.append(str(run_count)) # Jump directly to the start of the next run so each character is inspected once. run_start = run_endCompare full string lengths only at the end
Why wait until the entire string is encoded before deciding whether compression helped? Consider
s = "abc" + "d" * 20(length23): - Across the opening three runs,"abc"expands from3characters to6("a1b1c1"). - Yet the trailing"d" * 20shrinks from20characters to3("d20"), bringing the overall result"a1b1c1d20"to length9 < 23!Testing
len(compressed) < lengthat the end handles every boundary without extra branches: - Tie (len(compressed) == length):<evaluates toFalse, returnings. - Empty input (s = ""):encoded_partsstays[],compressedis"",0 < 0isFalse, and""is returned naturally.# Phase 2: Join pieces once in O(n) to avoid quadratic string-concatenation copies. compressed = "".join(encoded_parts) # Strict '<' ensures equal-length encodings (and empty string "") return the original `s`. if len(compressed) < length: return compressed return sWalk through all three examples step by step
Example 1: s = "mmmpqqqqqmm" (length = 11) [0..3) 'm' x 3 -> ['m', '3'] [3..4) 'p' x 1 -> ['m', '3', 'p', '1'] [4..9) 'q' x 5 -> ['m', '3', 'p', '1', 'q', '5'] [9..11) 'm' x 2 -> ['m', '3', 'p', '1', 'q', '5', 'm', '2'] compressed = "m3p1q5m2" (len 8 < 11) --> return "m3p1q5m2" Example 2: s = "xxxyzz" (length = 6) [0..3) 'x' x 3, [3..4) 'y' x 1, [4..6) 'z' x 2 -> compressed = "x3y1z2" (len 6, NOT < 6) --> return "xxxyzz" Example 3: s = "KKKKKKKKKKKKk" (length = 13) [0..12) 'K' x 12 -> ['K', '12'] [12..13) 'k' x 1 -> ['K', '12', 'k', '1'] compressed = "K12k1" (len 5 < 13) --> return "K12k1"Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def compress(s: str) -> str: """Run-length encode consecutive identical letters; keep s if not strictly shorter.""" length = len(s) # encoded_parts: flat list of strings alternating [char, decimal_count, ...], e.g. ['a', '2', 'b', '1']. encoded_parts: List[str] = [] # Phase 1: Scan maximal runs [run_start, run_end) of identical characters in one O(n) pass. run_start = 0 while run_start < length: # Advance run_end to the first index past the current run of s[run_start]. run_end = run_start while run_end < length and s[run_end] == s[run_start]: run_end += 1 # Every run (including length 1 and multi-digit counts >= 10) emits char + full decimal count. run_count = run_end - run_start encoded_parts.append(s[run_start]) encoded_parts.append(str(run_count)) # Jump directly to the start of the next run so each character is inspected once. run_start = run_end # Phase 2: Join pieces once in O(n) to avoid quadratic string-concatenation copies. compressed = "".join(encoded_parts) # Strict '<' ensures equal-length encodings (and empty string "") return the original `s`. if len(compressed) < length: return compressed return s✅ Submit now — all tests should pass.
Intuition & how it works
Imagine reading an inventory shelf aloud over a radio: instead of repeating "crate, crate, crate, crate, crate, drum", saying "crate 5, drum 1" is much shorter. Conversely, when almost nothing repeats ("bolt, nut, pin"), saying "bolt 1, nut 1, pin 1" doubles the message length—so reading the original list unchanged is strictly better!
This scheme is run-length encoding (RLE) (a compression format that replaces each contiguous streak of identical symbols with the symbol followed by its streak count). Two naive coding habits cause bugs or timeouts here: comparing s[i] against s[i - 1] easily forgets the final streak at the end of the loop, and building the output with result += ... can copy the entire prefix on every streak in O(n^2) time. Instead, we use a two-pointer scan (anchoring a streak at run_start and marching run_end forward until the letter changes), append pieces to a list in amortized O(1) time per append (occasional list resizes average out to constant work per item), join once at the end, and return the encoded string only when its length is strictly smaller than len(s).
Here is how the scan handles Example 1 ("mmmpqqqqqmm", length 11) versus Example 2 ("xxxyzz", length 6):
s = "mmmpqqqqqmm" (length 11):
run [0..3) "mmm" -> 'm', '3'
run [3..4) "p" -> 'p', '1'
run [4..9) "qqqqq" -> 'q', '5'
run [9..11) "mm" -> 'm', '2'
joined = "m3p1q5m2" (length 8 < 11) -> return "m3p1q5m2"
s = "xxxyzz" (length 6):
run [0..3) "xxx" -> 'x', '3'; run [3..4) "y" -> 'y', '1'; run [4..6) "zz" -> 'z', '2'
joined = "x3y1z2" (length 6 is NOT < 6) -> return "xxxyzz"
Complexity
Let n = len(s) be the length of the input string.
- Time:
O(n). Even with nestedwhileloops,run_endvisits each index from0ton - 1once beforerun_startjumps straight torun_end. Formattingstr(run_count)and joiningencoded_partsalso takeO(n)total work because a streak ofkcharacters produces1 + digits(k) <= k + 1output characters, capping the joined string at length2n. - Space:
O(n). On an alternating input like"ababab..."withnunit-length streaks,encoded_partsholds2nshort strings andcompressedholds2ncharacters before the final length comparison returnss.
Edge cases
- Empty string (
""):while run_start < 0performs zero iterations,compressedis"",0 < 0isFalse, and""is returned cleanly. - Single character (
"a"): Encodes to"a1"(length2 > 1), returning"a". - Equal-length tie (
"xxxyzz"->"x3y1z2","aa"->"a2"): Strict<rejects ties and returnssunchanged. - Shorter by one character (
"aaa"->"a3"): Length2 < 3, returning"a3". - Multi-digit counts (
"K" * 12 + "k"->"K12k1"):str(run_count)emits all base-10 digits ("12","100","100000"). - Case sensitivity and separated repeats (
"mmmpqqqqqmm","aaaAaaa"): Different cases split streaks ("a3A1a3"), and non-adjacent'm'streaks remain separate ("m3...m2"). - Prefix expansion followed by long streak (
"abc" + "d" * 20): Although"abc"expands into"a1b1c1", the complete result"a1b1c1d20"has length9 < 23and wins.
Common mistakes
- Dropping the final streak: Tracking
prev_charand emitting only whens[i] != prev_charskips the trailing run unless emit logic is duplicated after the loop. Therun_start/run_endloop handles every streak uniformly. - Writing
<=instead of<on the length check: Returningcompressedwhenlen(compressed) <= len(s)fails Example 2 ("xxxyzz"must return"xxxyzz", not"x3y1z2"). - Counting total letter frequencies (
collections.Counter): Merging non-adjacent streaks turns"mmmpqqqqqmm"into"m5p1q5", destroying positional order! - Suppressing
1on single-letter streaks: Emitting"p"instead of"p1"breaks the specification and miscomputes encoded length. - Aborting as soon as a prefix expands: Comparing partial output length against
run_endexits prematurely on"abc" + "d" * 20; early exit is valid only once running encoded length reaches the entire input lengthlen(s).
Alternative approaches
itertools.groupby(s): Standard-library grouping (for ch, group in groupby(s): count = sum(1 for _ in group)) achieves the sameO(n)time andO(n)space concisely, though interviewers generally look for explicit two-pointer boundary control.- Two-pass
O(1)-space precheck: First scansusing only integer counters to accumulate1 + len(str(run_count))across all streaks; if that sum is>= len(s), returnsimmediately without allocatingencoded_partsorcompressed.
Follow-up questions
- How could you avoid O(n) extra memory allocation when most input strings fail to shrink? Run a lightweight counting pass over
sfirst that sums1 + len(str(run_count))using only integer variables, aborting and returningsthe instant the running total reacheslen(s)(since every subsequent streak adds at least2characters). Only when Pass 1 finishes strictly belowlen(s)do you allocateencoded_partsof size< n, cutting auxiliary space on incompressible strings fromO(n)down toO(1). - How would you implement the inverse decompress function to recover the original string unambiguously? Because raw inputs contain exclusively letters
a–zandA–Zwhile every non-empty compressed string contains at least one digit, first checkif not any(ch.isdigit() for ch in t): return t(handling both""and any unchanged fallback string). Otherwise, walk each lettert[i], parse the full contiguous digit slicet[i + 1 : j]viaint(...), appendt[i] * countto an output buffer, and join once at the end. - What goes wrong if the input alphabet also allows digits '0'–'9', and how would you redesign the format? Two ambiguities collide:
"a112"could mean'a'repeated112times or'a'once followed by'1'twice, and an uncompressed fallback string like"a10"becomes indistinguishable from ten compressed'a's! Making the codec lossless over arbitrary bytes requires a delimiter-prefixed token format such as<count>#<char>(e.g.,"12#a"so the parser reads digits up to'#'and takes the very next character literally) paired with a 1-byte header flag ('R'for raw vs'C'for compressed).
Follow-up questions
- How could you avoid O(n) extra memory allocation when most input strings fail to shrink?
- How would you implement the inverse decompress function to recover the original string unambiguously?
- What goes wrong if the input alphabet also allows digits '0'–'9', and how would you redesign the format?
Similar questions
- Longest Ascending Orthogonal Path in a Matrix
- Kafka Consumer Architecture for Distributed Trace Grouping
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance