String Compression
Medium
Topics
Shorten a string of letters by run-length encoding. Split s into maximal runs of the same character. Write each run as its character, followed by the run's length in decimal only when the length is 2 or more. A run of one character is written as just that character. Return the encoded string.
Letters are case-sensitive, so "a" and "A" are different characters. A run longer than 9 contributes all of its digits, for example twelve bs become "b12".
On this judge you return the encoded string. The common in-place variant writes the same encoding into the input array and returns its length; the run-splitting logic is identical.
Example 1
x2yz3.Input: s = "xxyzzz" Output: "x2yz3"
Example 2
Input: s = "q" Output: "q"
Example 3
Input: s = "mnnnnnnnnnnnnn" Output: "mn13" Explanation: One m, then thirteen n.
Constraints
- 1 <= s.length <= 2000
- s consists of uppercase and lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
A run ends exactly where the next character differs from the current one. So one left-to-right pass with a pointer at the start of the current run is enough: advance a second pointer until the character changes, and the distance between them is the run length.
Approach
- Set
i = 0. - Move
jforward fromiwhiles[j] == s[i]. - Append
s[i], then appendj - ias decimal text if it is greater than 1. - Set
i = jand repeat until the end. Build the output in a string builder or list rather than with repeated concatenation.
Dry Run
s = "xxyzzz"
s[0..1] is "xx" run of 2 append the char and the count out "x2"
s[2..2] is "y" run of 1 append the char only out "x2y"
s[3..5] is "zzz" run of 3 append the char and the count out "x2yz3"
answer "x2yz3"
The inner `while` finds the end of the run, so the outer loop jumps straight to
`i = j` and every character is examined once. That also means the final run is
flushed inside the loop rather than after it -- there is no leftover state to
handle on exit.
A run of ONE emits no count. That is the most common wrong answer here: append the
count unconditionally and "xxyzzz" becomes "x2y1z3", which is both longer than the
input and not what the problem asks for.
The count is appended as a string, not as a single character. `str(j - i)` handles
multi-digit runs, so twelve a's compress to "a12"; building the digit with
something like char('0' + count) silently breaks at 10.Complexity
- Time — O(n): each character is read once.
- Space — O(n): for the output; the in-place variant needs O(1) because the encoding is never longer than the input.
Common Pitfalls
- Appending a single digit with
char('0' + count)breaks for runs of 10 or more. - Writing
"a1"for a run of one is the most common wrong answer. - Forgetting to flush the final run after the loop.
Full Solution — all languages
class Solution:
def compress(self, s):
if not s:
return ""
out = []
i = 0
while i < len(s):
j = i
while j < len(s) and s[j] == s[i]:
j += 1
out.append(s[i])
if j - i > 1:
out.append(str(j - i))
i = j
return "".join(out)import java.util.*;
class Solution {
public String compress(String s) {
if (s.isEmpty()) return "";
StringBuilder out = new StringBuilder();
int i = 0;
while (i < s.length()) {
int j = i;
while (j < s.length() && s.charAt(j) == s.charAt(i)) j++;
out.append(s.charAt(i));
if (j - i > 1) out.append(j - i);
i = j;
}
return out.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string compress(string s) {
if (s.empty()) return "";
string out;
size_t i = 0;
while (i < s.size()) {
size_t j = i;
while (j < s.size() && s[j] == s[i]) j++;
out += s[i];
if (j - i > 1) out += to_string(j - i);
i = j;
}
return out;
}
};/**
* @param {string} s
* @return {string}
*/ var compress = function(s) {
if (!s.length) return "";
let out = "", i = 0;
while (i < s.length) {
let j = i;
while (j < s.length && s[j] === s[i]) j++;
out += s[i];
if (j - i > 1) out += String(j - i);
i = j;
}
return out;
};