Facebook Pixel

Compress String with Limited Repetition

JavaScript
medium
20 mins

Given a string consisting of lowercase alphabetic characters, compress the string by replacing consecutive repeated characters with the character followed by the count of its repetitions.

However, to keep the count readable, if the count of consecutive repeated characters exceeds 9, split the count into chunks of at most 9.

If a character appears only once consecutively, do not append a count after it.


Input

  • A string str containing only lowercase English letters (a-z).
  • Length of str is between 0 and 10^5.

Output

  • A compressed string where consecutive repeated characters are replaced by the character followed by the count, with no count larger than 9.
  • Single occurrences of a character are left as-is (no trailing 1).

Examples

  1. Input: "aaabbbccccccccccc" Output: "a3b3c9c2" Explanation:

    • 'a' is repeated 3 times → "a3"
    • 'b' is repeated 3 times → "b3"
    • 'c' is repeated 11 times → split as "c9c2" (since count can't exceed 9)
  2. Input: "xxxxxxxxxxxx" Output: "x9x3" Explanation:

    • 'x' is repeated 12 times → split as "x9x3"
  3. Input: "abc" Output: "abc" Explanation:

    • No characters are repeated consecutively, so the string is returned as-is.
  4. Input: "aabbccddeeeeee" Output: "a2b2c2d2e6" Explanation:

    • Each character is repeated consecutively and count is ≤ 9, so just append the count directly.

Edge Cases

  • Empty string input should return an empty string.
  • Very long sequences of the same character must correctly split counts into chunks of 9 or less.
  • Strings with no consecutive repeats remain unchanged.
  • Single character input returns the character itself.

Companies:

amazon
microsoft

Solve Similar questions 🔥

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.