β Back to Revisions
Day 9
View Problem βCompress String (Run-Length Encoding)
π
October 31, 2025π·οΈ Smart Interviews
Complexity Analysis
Brute Force
N/A
Optimized
N/A
Space
N/A
Solutions
Pythonπ
import sys
def solve_compress_string():
try:
S = sys.stdin.readline().strip()
except:
return
if not S:
print("")
return
# Optimal: O(N) Time, O(N) Space - Single Pass with Counting
compressed = []
i = 0
N = len(S)
while i < N:
current_char = S[i]
count = 0
j = i
# Count the consecutive run
while j < N and S[j] == current_char:
count += 1
j += 1
# Append character and count
compressed.append(current_char)
compressed.append(str(count))
# Move i to the start of the next run
i = j
print("".join(compressed))
# Brute Force is effectively the same logic (O(N))
def solve_compress_string_brute():
solve_compress_string()
if __name__ == "__main__":
solve_compress_string()Javaβ
import java.util.Scanner;
class Solution {
// O(N) Time, O(N) Space - Optimal (Single Pass with Counting)
public static void solve_compress_string() {
Scanner scanner = new Scanner(System.in);
if (!scanner.hasNextLine()) return;
String S = scanner.nextLine();
if (S.isEmpty()) {
System.out.println("");
scanner.close();
return;
}
StringBuilder compressed = new StringBuilder();
int N = S.length();
int i = 0;
while (i < N) {
char currentChar = S.charAt(i);
int count = 0;
int j = i;
// Count the consecutive run
while (j < N && S.charAt(j) == currentChar) {
count++;
j++;
}
// Append character and count
compressed.append(currentChar).append(count);
// Move i to the start of the next run
i = j;
}
System.out.println(compressed.toString());
scanner.close();
}
public static void main(String[] args) {
solve_compress_string();
}
}C++β‘
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
// O(N) Time, O(N) Space - Optimal (Single Pass with Counting)
void solve_compress_string() {
string S;
if (!getline(cin, S) || S.empty()) {
cout << "" << endl;
return;
}
stringstream compressed;
int N = S.length();
int i = 0;
while (i < N) {
char current_char = S[i];
int count = 0;
int j = i;
// Count the consecutive run
while (j < N && S[j] == current_char) {
count++;
j++;
}
// Append character and count
compressed << current_char << count;
// Move i to the start of the next run
i = j;
}
cout << compressed.str() << endl;
}
void solve_compress_string_brute() {
solve_compress_string();
}
int main() {
solve_compress_string();
return 0;
}Tags
stringtwo-pointersencoding
π‘ Revision Tips
- β’ Try solving from memory before checking your solution
- β’ Focus on the approach and pattern, not just the code
- β’ Can you explain the solution to someone else?
- β’ Try implementing in a different language