Ctrl K

Packing Runs in Place

Medium
You are given an array of characters symbols. Pack it like this: walk through the array and replace each run of identical consecutive characters with the character itself, followed by the run's length if the run is longer than one. The length is written digit by digit, each digit as a separate element: a run of 12 b characters becomes "b", "1", "2". Write the packed result into the front of the same symbols array and return its length. Whatever remains in the array past that length does not matter. Try to use only O(1) extra memory.
Example 1
symbols=["x", "x", "x", "y", "z", "z"] → 5

The runs xxx, y and zz pack into x3yz2, which is 5 symbols.

Example 2
symbols=["q"] → 1

A single symbol stays as it is.

Example 3
symbols=["k", "k", "k", "k", "k", "k", "k", "k", "k", "k", "k", "m"] → 4

Eleven k in a row become k11, with the length stored as two separate symbols "1" and "1". Together with m that gives k11m, 4 symbols.

Constraints
  • 1 ≤ len(symbols) ≤ 2000
  • symbols[i] is an English letter (lowercase or uppercase), a digit or a printable symbol
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Mirror Fragment MediumWords in Reverse Order MediumExactly One Edit Apart MediumWhich Release Is Newer MediumReverse the Word Order in Place Medium
loading Python…
Input
symbols=["x", "x", "x", "y", "z", "z"]
Expected
5

Run checks the first 3 tests in your browser. Submit checks all 28 tests on the server, hidden ones included.