Code Logo

Run-Length Encoding

Published at25 Jul 2026
Medium 0 views
Like0

Perform run-length encoding on a string. Consecutive identical characters are replaced by the character followed by the count. For example, "aaabbc" becomes "a3b2c1".

Iterate through the string, tracking the current character and its count. When a different character is encountered, append the previous character and its count to the result, then start counting the new character.

Time complexity is O(n) and space is O(n) for the result. This is a lossless compression technique that works well for strings with many repeated consecutive characters.

Example Input & Output

Example 1
Input
"aaabbc"
Output
"a3b2c1"
Explanation

3 a's, 2 b's, 1 c

Example 2
Input
"aaa"
Output
"a3"
Explanation

All same

Example 3
Input
"abc"
Output
"a1b1c1"
Explanation

Each char appears once

Example 4
Input
""
Output
""
Explanation

Empty string

Example 5
Input
"a"
Output
"a1"
Explanation

Single char

Algorithm Flow

Recommendation Algorithm Flow for Run-Length Encoding
Recommendation Algorithm Flow for Run-Length Encoding

Solution Approach

function solution(s) {
  if (s.length === 0) return '';
  var result = '', count = 1;
  for (var i = 1; i <= s.length; i++) {
    if (i < s.length && s.charAt(i) === s.charAt(i - 1)) { count++; }
    else { result += s.charAt(i - 1) + count; count = 1; }
  }
  return result;
}

Best Answers

java
class Solution {
    public String solution(String s) {
        if(s.isEmpty())return"";StringBuilder r=new StringBuilder();int c=1;
        for(int i=1;i<=s.length();i++){
            if(i<s.length()&&s.charAt(i)==s.charAt(i-1))c++;
            else{r.append(s.charAt(i-1)).append(c);c=1;}
        }return r.toString();
    }
}