You are given chars, a list of single characters. Squash it: every run of the same character next to each other becomes that character, followed by the run's length when the length is 2 or more. A run of one stays as just the character. A length of 10 or more is written one digit per cell, so a run of 12 becomes three cells: the character, 1 and 2.
Write the squashed result over the start of chars itself, using only a constant amount of extra memory, and return its length. Cells after that length can hold anything.
Example 1
Input: chars = ["x","x","x","y","z","z"] Output: 5, chars = ["x","3","y","z","2", _] Why: xxx, y, zz becomes x3 y z2
2 more examples and the constraints
Example 2
Input: chars = ["q"] Output: 1, chars = ["q"] Why: a run of one gets no number
Example 3
Input: chars = ["p","p","p","p","p","p","p","p","p","p","r"] Output: 4, chars = ["p","1","0","r", ...] Why: ten p's become p10, then r
Constraints
- 1 ≤ length of chars ≤ 2,000
- Each cell is a letter (either case), a digit or a symbol
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Build a new stringO(n)
- Read and write pointersO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 2,000 characters | Verdict |
|---|---|---|---|
| Build a new string | O(n) | Fast, but uses O(n) extra space | |
| Read and write pointers | O(n) | Best; in place, one pass |
n = length of chars.
Edge cases to test
- One character. ["q"] stays ["q"] and the answer is 1.
- Run of 10 or more. Ten p's need two digit cells, 1 and 0, not one cell holding "10".
- No runs at all. ["a","b","c"] is unchanged and the answer is 3.
- Digits as input. ["7","7","7"] becomes ["7","3"]: digit characters are compressed like any other.
- One long run. 2,000 copies of one character become that character and 2, 0, 0, 0.
Common mistakes
- Writing the count 1 for single characters.
- Putting a count like 12 into one cell instead of one cell per digit.
- Forgetting the last group, because the loop only writes when it sees the character change.
How to talk through it
- 1Clarify. Is a run of one written without a number? How are counts of 10 or more stored?
- 2Give the simple version. Build the compressed string separately and copy it back; O(n) time but O(n) space.
- 3Argue it fits in place. A run never gets longer when compressed, so the writer stays behind the reader.
- 4Code the two pointers. Read to the end of a run, write the character, then the digits of the count.
- 5Test out loud. Run a single character, a run of 10 and a list with no repeats.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?