← Back to index
MediumTypeScript3 min read

String Compression

compress string in-place by replacing consecutive characters with character and count using two pointers.

two-pointersstring

Problem link

View on LeetCode

Solutions in this repo

  • TypeScript../Typescript/string-compression/solution.tsTypeScript solution

use two pointers: read pointer scans ahead to count consecutive characters, write pointer writes compressed result. for each group, write the character, then the count if it's greater than 1.

the key is in-place modification: we overwrite the array as we go, tracking where to write next. truncate the array to the write position at the end.

algorithm

  • read pointer: finds end of current character group
  • write pointer: writes compressed representation
  • only write count if count > 1
  • truncate array to final write position

complexity

O(n) time: single pass through the array. O(1) space excluding input array. efficient in-place compression.