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!

Create an Account

Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.

Create account

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 Feb 2026

Contest runs February 1 - 28. Complete challenges to climb the leaderboard!

Points are calculated for challenges completed during the contest period.