 All Problems
String Compression
easy
strings
two pointers
amazon
microsoft
apple
swiggy

Given a string s, perform basic string compression using the counts of repeated characters. If a character appears once, just write the character. If it appears more than once, write the character followed by the count.

If the compressed string is not smaller than the original, return the original string.

Example 1:

Input: aabcccccaaa
Output: a2bc5a3

Example 2:

Input: abcd
Output: abcd

Example 3:

Input: aabb
Output: aabb

Constraints:

  • 1 ≤ s.length ≤ 10⁵
  • s consists of lowercase English letters

Input format: A single line string.

Output format: Compressed string, or original if compressed is not shorter.

Run to check your code against the sample cases, or submit to run every case