String Compression

MediumTwo Pointerstwo pointers

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an array of characters chars. Compress it by processing each maximal group of consecutive equal characters: write the character once, and if the group has length greater than 1, follow it with the decimal digits of the length, each digit as its own array entry. Groups of length 1 are written as just the character. Equal characters that are not adjacent form separate groups. Return the compressed array. (In the classic version you overwrite chars in place and return the new length; the harness asks you to return the compressed prefix instead. The compressed form is never longer than the input, so the in-place two-pointer approach with O(1) extra space works.)

Examples

Input: chars = ["a","a","b","c","c","c"]
Output: ["a","2","b","c","3"]
Groups are aa, b, ccc.
Input: chars = ["z","z","z","z","z","z","z","z","z","z","z","z"]
Output: ["z","1","2"]
A group of 12 writes two digit entries.

Constraints

  • 1 <= chars.length <= 2000
  • `chars[i]` is a lowercase or uppercase English letter, a digit, or a symbol

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More two pointers problems