The two-pointer approach is the way to go here.
Use a two-pointer technique: one pointer reads through the array to identify runs of identical characters, while the other writes the compressed output in place. For each run, write the character and then the count as individual digits, updating the write pointer accordingly. Return the final write pointer as the new length.
Pro tip: Clarify edge cases upfront, such as runs longer than 9 (requiring multiple digits) and single-character runs (no count written). Also, mention that the array beyond the new length is irrelevant, so overwriting is safe.
Set a read pointer to traverse the array and a write pointer to track the compressed output position. Also, keep a variable to count consecutive identical characters.
While the read pointer is within bounds, count how many times the current character repeats consecutively by advancing the read pointer.
Write the character at the write pointer, then if the count is greater than 1, convert the count to digits and write each digit individually.
After writing, update the write pointer and continue the loop until the read pointer reaches the end of the array.
The write pointer now indicates the length of the compressed array. Return it as the result.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.