← Salesforce Interview Insights
The basic logic clicks pretty fast: iterate, count runs, write back.
Use a two-pointer technique: one pointer to read through the array and another to write the compressed result in-place. For each group of consecutive identical characters, write the character followed by the digits of its count, handling counts of 10 or more by writing each digit separately. Finally, return the write pointer as the new length.
Pro tip: Clarify that the array may have extra space beyond the new length, and that only the first 'new length' characters matter. Also, mention that the algorithm runs in O(n) time and O(1) space, which is optimal.
Set a read pointer (i) to 0 and a write pointer (write) to 0. The read pointer will scan the original array, and the write pointer will track the position for the next compressed character.
While i < length of array, identify the current character and count how many times it repeats consecutively by advancing a second pointer (j) until the character changes.
Write the current character at the write pointer and increment it. If the count is greater than 1, convert the count to a string and write each digit individually at the write pointer, incrementing it for each digit.
Set i = j to move to the next group of characters.
After the loop, return the write pointer as the new length of the compressed array.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.