2dbi

String Compression

viaLeetCode

Problem Compress a character array in place using run-length encoding: each run of consecutive repeating characters becomes the character followed by its count (count omitted when 1). Return the new length. String variant: "abaabbbc" → "aba2b3c".

Input / Output

  • Input: char[] chars.
  • Output: new length k; the first k slots of chars hold the compressed result. Counts >= 10 are written digit by digit.

Constraints

  • 1 <= n <= 2000 required O(n) time, O(1) extra space (in-place is the point).

Example

  • ["a","a","b","b","c","c","c"] → 6, chars = ["a","2","b","2","c","3"]
  • ["a","b","b","b","b","b","b","b","b","b","b","b","b"] → 4, ["a","b","1","2"]

Expected approach

  • Two pointers: read pointer scans runs, write pointer emits char + count digits. Careful with multi-digit counts and the count==1 rule. O(n) time, O(1) space. Clarify whether compression should be skipped when the "compressed" form is longer (classic interview twist).
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account