mediumStringsPattern: Mixed

Consecutive Character Encoder Solution

Problem Statement

Given a string s consisting of lowercase English letters, implement 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 output, and sequences of exactly two identical letters are left uncompressed.

Examples

Example 1:
Input:aaabbbccc
Output:a3b3c3
Example 2:
Input:abc
Output:abc
Example 3:
Input:aabbcc
Output:aabbcc

Constraints

  • The input string will only contain lowercase English letters.
  • The length of the input string will be between 97 and 6787 characters (inclusive).
Time: O(n) Space: O(n)
A more efficient solution involves iterating over the string once and using a counter to keep track of consecutive occurrences of each letter. This approach would have a linear time complexity.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.