Problem 277966 · easy · Level 02 Linear Data Structures

Run Counts

strings · compression · iteration

Write rle_encode(s) that compresses a string by replacing every run of equal consecutive characters with the run length followed by the character. A count of 1 is omitted.

Examples

Input:  s = "aaabcc"
Output: "3ab2c"

Input:  s = "abc"
Output: "abc"

Input:  s = ""
Output: ""

Constraints

  • 0 <= len(s) <= 10**5, letters only (no digits, so the output is unambiguous)
  • Runs can be longer than 9, so counts may have several digits
  • Target: O(n) time

Goals

  • Detect where a run of equal characters ends
  • Build the output with a list and join
  • Emit a count only when it carries information
Starting Python…