#443

String Compression

Medium Read/write pointers

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Compress a char array in place: each run of a repeated character becomes the character followed by the run length (only if the length is more than 1). Return the new length.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: in place, write each letter followed by its run length (if more than 1).

Why this works: read a whole run, write the letter and the digits of the count; the write pointer never passes the read pointer.

Example: [a, a, b, b, c, c, c]

a×2 → "a2", b×2 → "b2", c×3 → "c3"[a, 2, b, 2, c, 3] → length 6

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Writing the count as a single char (char) count, which breaks for runs of 10+.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Strings
🎬 Episodes 16–20: video coming soon