Skip to content
CodeKruPro

Compress a string with run counts (aaabb to a3b2)

Coding problemEasy-MediumAsked in: Fivetran, TCS

Given a string s of English letters, replace every run of the same letter by that letter followed by the length of the run. Return the result.

Every run gets its count, even a run of one: "abc" becomes "a1b1c1". Counts of 10 or more are written in full ("a12"). Upper and lower case are different letters. An empty string gives an empty string.

Examples

Example 1
Input: s = "aabcccccaaa"
Output: "a2b1c5a3"
Example 2
Input: s = "aaabb"
Output: "a3b2"
Example 3
Input: s = "aA"
Output: "a1A1"

Constraints

  • The length of s is between 0 and 100,000
  • s holds English letters only

Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.

Run your code to see the results here.

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in