String Compression — Solution in Python, Java & C++
String Compression solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. A medium problem.
String Compression is a medium coding problem on strings and two pointers, asked in Amazon, Google, Microsoft and Adobe interviews.
- Difficulty: Medium
- Topics: Strings, Two Pointers
- Asked at: Amazon, Google, Microsoft, Adobe, Snapchat, Yelp, Palantir, Spotify
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Compress a string using run-length encoding: replace each maximal run of a repeated character by that character followed by the run length. A run of length 1 is written as the character alone, with no number.
Return the compressed string.
Example 1
Input: chars = "aabbccc"
Output: a2b2c3
Example 2
Input: chars = "a"
Output: a
Explanation: A run of one keeps no count.
Example 3
Input: chars = "abbbbbbbbbbbb"
Output: ab12
Explanation: Multi-digit counts are written out in full.
Constraints
1 <= chars.length <= 40chars consists of lowercase English letters.
Follow-up: The interview version modifies the character array in place and returns the new length, using O(1) extra space.
Hints for String Compression
Hint 1
Walk the string with a run-start index and a scanning index.
Hint 2
Append the character, and append the count only when the run is longer than one.
Hint 3
Counts of ten or more contribute several characters — write the whole number, not one digit.
How to solve String Compression
Scan runs of identical characters; emit the character, then its length only when the run exceeds one.
Approach
- With
iat the run start, advancejwhilechars[j] == chars[i]. - Append
chars[i]; ifj - i > 1, append the decimal digits ofj - i. - Set
i = jand repeat.
Why it works
Maximal runs partition the string, and the rules specify exactly the character-plus-count representation with the count omitted for singletons.
Complexity
- Time —
O(n) - Space —
O(n) for the output
Pitfalls
- A count of 10 or more contributes multiple characters — write the full number.
- The in-place array version writes with a separate write pointer and returns the new length.
Reference solution
Python
def compress(chars: str) -> str:
out = []
i = 0
while i < len(chars):
j = i
while j < len(chars) and chars[j] == chars[i]:
j += 1
out.append(chars[i])
if j - i > 1:
out.append(str(j - i))
i = j
return "".join(out)Java
public static String compress(String chars) {
StringBuilder out = new StringBuilder();
int i = 0;
while (i < chars.length()) {
int j = i;
while (j < chars.length() && chars.charAt(j) == chars.charAt(i)) j++;
out.append(chars.charAt(i));
if (j - i > 1) out.append(j - i);
i = j;
}
return out.toString();
}C++
string compress(string chars) {
string out = "";
int i = 0;
int n = (int) chars.size();
while (i < n) {
int j = i;
while (j < n && chars[j] == chars[i]) j++;
out += chars[i];
if (j - i > 1) out += to_string(j - i);
i = j;
}
return out;
}JavaScript
var compress = function(chars) {
let out = "";
let i = 0;
while (i < chars.length) {
let j = i;
while (j < chars.length && chars[j] === chars[i]) j++;
out += chars[i];
if (j - i > 1) out += String(j - i);
i = j;
}
return out;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings · Two Pointers Technique