Compress a string by replacing consecutive repeated characters with the character followed by its count. For example, "aabbbcc" becomes "a2b3c2". If the compressed string is not shorter than the original, return the original string. Return null for null input and empty string for empty input.
Examples:
Input: str = 'aabbbcc'
Output: 'a2b3c2'
Explanation: a appears 2 times, b appears 3 times, c appears 2 times
Input: str = 'abc'
Output: 'abc'
Explanation: Compressed would be 'a1b1c1' which is longer, so return original
Input: str = 'aaa'
Output: 'a3'
Explanation: a appears 3 times, compressed is shorter
Input: str = null
Output: null
Explanation: Null input returns null
Input: str = ''
Output: ''
Explanation: Empty string returns empty string
Apex Code Editor
Welcome to Lightning Challenge!
How It Works
- • Write your solution in the code editor
- • Connect your Salesforce org to test
- • Submit to check if your solution passes
- • Use hints if you get stuck
Contest Alert
🏆 #CodeEveryDay October 2026 (Oct 4–15)Sponsored by FLXBL
Contest runs October 4 - 15. Complete challenges to climb the leaderboard!
Prizes 1 & 2: Salesforce certification exam voucher — won by random drawing, where every point is a ticket. see all prizes
Only the 12 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.