Compress a String by Run-Length Counts, Keeping the Original When Not Shorter
Company: New Relic
Role: Backend Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Implement run-length string compression that replaces each run of repeated characters with the character and its count, returning the original string when the compressed form is not strictly shorter. Tests careful run handling, multi-digit counts, the tie rule, and complexity and edge-case discussion.
Read the full New Relic Backend Engineer interview experience this question came from
Constraints
- 0 <= len(s) <= 10^5
- s contains only English letters, 'a' to 'z' and 'A' to 'Z'.
Examples
Input: ('',)
Expected Output: ''
Explanation: Empty string: the empty compression is not shorter, so the empty string is returned.
Input: ('a',)
Expected Output: 'a'
Explanation: Single character: a1 is longer than a, so the original is returned.
Hints
- A run ends where the next character differs from the current one or where the string ends; make sure the last run is written out too.
- Run lengths of 10 or more need every decimal digit, and 'a' and 'A' never belong to the same run.
- Build the whole compressed string before comparing lengths, and remember that an equal length keeps the original.