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 s from 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 10 or more characters write out every decimal digit (12 consecutive '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 if len(encoded) < len(s); whenever len(encoded) >= len(s), return s as-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^5
  • s consists solely of ASCII English letters ('a'–'z' and 'A'–'Z').

Step-by-step walkthrough

  1. Understand when run-length encoding actually shrinks a string

    Given a string s of up to 100,000 ASCII 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 of 2 ("mm" -> "m2") breaks even at 2 characters. - Only streaks of 3 or longer ("qqqqq" -> "q5") save characters!

    Four details must hold simultaneously: 1. Case-sensitive comparison: 'K' and 'k' never merge into one run ("KKKKKKKKKKKKk" splits into 12 'K's and 1 '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 if len(compressed) < len(s). Ties ("xxxyzz" vs "x3y1z2") and expansions ("abc" vs "a1b1c1") return s unchanged.

  2. 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 of s unless you duplicate the emit code outside the loop!

    Using two indices, run_start and run_end, eliminates that special case: 1. run_start marks the opening index of the current streak. 2. run_end begins at run_start and steps right while run_end < length and s[run_end] == s[run_start]. 3. Once run_end stops, the streak occupies s[run_start : run_end], so its count is run_end - run_start. 4. Advance run_start = run_end to 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 = 3
    

    Although one while loop sits nested inside another while loop, total work is O(n) linear time, not O(n^2): run_end advances monotonically from 0 to length, inspecting each index once across the entire function call.

  3. Collect pieces in a list to avoid quadratic copying

    Python strings are immutable. Appending directly via compressed += piece inside a loop can allocate a new string and copy all accumulated characters on every streak, degrading to O(n^2) on alternating strings like "abababab..." with 50,000 length-1 runs.

    Instead, append each character and str(run_count) to a list encoded_parts (O(1) amortized per append), then call "".join(encoded_parts) once at the end to build the output string in a single O(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_end
    
  4. Compare 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 (length 23): - Across the opening three runs, "abc" expands from 3 characters to 6 ("a1b1c1"). - Yet the trailing "d" * 20 shrinks from 20 characters to 3 ("d20"), bringing the overall result "a1b1c1d20" to length 9 < 23!

    Testing len(compressed) < length at the end handles every boundary without extra branches: - Tie (len(compressed) == length): < evaluates to False, returning s. - Empty input (s = ""): encoded_parts stays [], compressed is "", 0 < 0 is False, 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 s
    
  5. Walk 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"
    
  6. 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 nested while loops, run_end visits each index from 0 to n - 1 once before run_start jumps straight to run_end. Formatting str(run_count) and joining encoded_parts also take O(n) total work because a streak of k characters produces 1 + digits(k) <= k + 1 output characters, capping the joined string at length 2n.
  • Space: O(n). On an alternating input like "ababab..." with n unit-length streaks, encoded_parts holds 2n short strings and compressed holds 2n characters before the final length comparison returns s.

Edge cases

  • Empty string (""): while run_start < 0 performs zero iterations, compressed is "", 0 < 0 is False, and "" is returned cleanly.
  • Single character ("a"): Encodes to "a1" (length 2 > 1), returning "a".
  • Equal-length tie ("xxxyzz" -> "x3y1z2", "aa" -> "a2"): Strict < rejects ties and returns s unchanged.
  • Shorter by one character ("aaa" -> "a3"): Length 2 < 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 length 9 < 23 and wins.

Common mistakes

  • Dropping the final streak: Tracking prev_char and emitting only when s[i] != prev_char skips the trailing run unless emit logic is duplicated after the loop. The run_start / run_end loop handles every streak uniformly.
  • Writing <= instead of < on the length check: Returning compressed when len(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 1 on 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_end exits prematurely on "abc" + "d" * 20; early exit is valid only once running encoded length reaches the entire input length len(s).

Alternative approaches

  • itertools.groupby(s): Standard-library grouping (for ch, group in groupby(s): count = sum(1 for _ in group)) achieves the same O(n) time and O(n) space concisely, though interviewers generally look for explicit two-pointer boundary control.
  • Two-pass O(1)-space precheck: First scan s using only integer counters to accumulate 1 + len(str(run_count)) across all streaks; if that sum is >= len(s), return s immediately without allocating encoded_parts or compressed.

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 s first that sums 1 + len(str(run_count)) using only integer variables, aborting and returning s the instant the running total reaches len(s) (since every subsequent streak adds at least 2 characters). Only when Pass 1 finishes strictly below len(s) do you allocate encoded_parts of size < n, cutting auxiliary space on incompressible strings from O(n) down to O(1).
  • How would you implement the inverse decompress function to recover the original string unambiguously? Because raw inputs contain exclusively letters a–z and A–Z while every non-empty compressed string contains at least one digit, first check if not any(ch.isdigit() for ch in t): return t (handling both "" and any unchanged fallback string). Otherwise, walk each letter t[i], parse the full contiguous digit slice t[i + 1 : j] via int(...), append t[i] * count to 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' repeated 112 times 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

Similar questions

More New Relic interview questions

All 3 New Relic questions →