Code Logo

Run-Length Encoding

Published at25 Jul 2026
Medium 0 views
Like0

Given a string, perform run-length encoding: replace consecutive repeated characters with the character followed by the count. For example, "aaabbc" becomes "a3b2c1". If a character appears only once, include it with a count of 1.

For example, encoding "hello" produces "h1e1l2o1". Encoding "aabbbcc" produces "a2b3c2". An empty string returns "". A single character "x" returns "x1".

Run-length encoding is a simple form of data compression. It replaces repeated characters with a count, reducing storage for data with long runs of identical values. It is used in bitmap image compression (BMP, PCX) and as a building block for more advanced compression algorithms.

The solution iterates through the string, counting consecutive occurrences of each character. When the character changes or the end is reached, append the character and its count to the result.

Edge cases include an empty string (return ""), a string with all unique characters (each followed by "1"), and a string with a single character repeated many times.

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

Solution Approach

Iterate through the string, counting consecutive identical characters and appending each with its count.

function runLengthEncode(s)
  if s is empty then return ""
  result = ""
  count = 1
  for i = 1 to length(s) - 1
    if s[i] == s[i-1] then count = count + 1
    else
      result = result + s[i-1] + count
      count = 1
  result = result + s[length(s)-1] + count
  return result

Handle empty string. Start with count = 1 for the first character. Loop from index 1: if the current character matches the previous, increment count. Otherwise, append the previous character and its count to the result, then reset count to 1. After the loop, append the last character and its final count.

Time complexity is O(n), space complexity is O(n) for the 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();
    }
}