Run-Length Encoding of a String

Problem

Compress a string using run-length encoding: replace runs of the same character with the character followed by its count.

Input:  s = "aaabbcccc"
Output: "a3b2c4"

Python Solution

def run_length_encode(s):
    if not s:
        return ""
    result = []
    count = 1
    for i in range(1, len(s) + 1):
        if i < len(s) and s[i] == s[i - 1]:
            count += 1
        else:
            result.append(s[i - 1] + str(count))
            count = 1
    return "".join(result)

C++ Solution

string runLengthEncode(string s) {
    if (s.empty()) return "";
    string result;
    int count = 1;
    for (int i = 1; i <= s.size(); i++) {
        if (i < s.size() && s[i] == s[i - 1]) {
            count++;
        } else {
            result += s[i - 1] + to_string(count);
            count = 1;
        }
    }
    return result;
}

Java Solution

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

Complexity

Time: O(n) — one pass counting consecutive runs. Space: O(n) in the worst case for the output, though typically much shorter than the input for strings with long runs.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.