BackmediumStrings Razorpay

Galactic Transmission Encoding Solution

Problem Statement

Given a string of 97 to 6787 characters consisting of lowercase English letters representing signal patterns, write a function to compress it using a custom encoding where sequences of the same letters are replaced by the letter followed by the count of its consecutive occurrences, except when the count is 1, in which case only the letter is written.

Example 1
Input
aabcccccaaa
Output
a2b1c5a3

Explanation: Step-by-step: with input 'aabcccccaaa', we encounter 'a' for the first time, so we append 'a1'. Then we encounter 'a' again, so we append 'a1'. Next, we encounter 'b' for the first time, so we append 'b1'. Then we encounter 'c' for the first time, so we append 'c1'. After that, we encounter 'c' again, so we append 'c1'. We keep doing this until we reach the end of the string, giving output 'a2b1c5a3'.

Example 2
Input
xxyyzz
Output
x2y2z2

Explanation: Step-by-step: with input 'xxyyzz', we encounter 'x' for the first time, so we append 'x1'. Then we encounter 'x' again, so we append 'x1'. Next, we encounter 'y' for the first time, so we append 'y1'. Then we encounter 'y' again, so we append 'y1'. After that, we encounter 'z' for the first time, so we append 'z1'. We keep doing this until we reach the end of the string, giving output 'x2y2z2'.

Constraints

  • The input string will only contain lowercase English letters.
  • The length of the input string will be between 97 and 6787 characters (inclusive).
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free