443. String Compression
Asked at 38Apple57Bloomberg55Amazon55Microsoft51Google44Meta43Salesforce88Yandex82Goldman Sachs62Pinterest49CrowdStrike100GoDaddy97Yelp94Expedia91Rakuten88Ripple82Rivian81Snap80ServiceNow79Tinkoff75Paytm71Lyft70The Trade Desk69Zoox66Palo Alto Networks65MongoDB61EPAM Systems60Anduril55Nvidia55Accenture54eBay53Affirm52Cognizant48Oracle45Visa39IBM35TikTok35tcs27
Problem
Compress the character array chars in place: each run of a repeated character becomes the character followed by the run length when it is longer than 1 (lengths of 10 or more take several characters). Return the new length.
Example: ["a","a","b","b","c","c","c"] → 6, with chars starting ["a","2","b","2","c","3"]
Constraints: O(1) extra space.
Read pointer finds each run [i, j); write pointer writes the character and, if the run is longer than 1, the digits of its length. The write pointer never overtakes the read pointer, so it works in place.
Complexity: O(n) time, O(1) extra space.
class Solution:
def compress(self, chars: List[str]) -> int:
w = i = 0
while i < len(chars):
j = i
while j < len(chars) and chars[j] == chars[i]:
j += 1
chars[w] = chars[i]
w += 1
if j - i > 1:
for d in str(j - i):
chars[w] = d
w += 1
i = j
return w
a = ["a", "a", "b", "b", "c", "c", "c"]
k = Solution().compress(a)
assert k == 6 and a[:k] == ["a", "2", "b", "2", "c", "3"]
a = ["a"]
k = Solution().compress(a)
assert k == 1 and a[:k] == ["a"]
a = ["a"] + ["b"] * 12
k = Solution().compress(a)
assert k == 4 and a[:k] == ["a", "b", "1", "2"]
class Solution {
public int compress(char[] chars) {
int w = 0;
for (int i = 0, j; i < chars.length; i = j) {
for (j = i; j < chars.length && chars[j] == chars[i]; j++) ;
chars[w++] = chars[i];
if (j - i > 1) for (char d : String.valueOf(j - i).toCharArray()) chars[w++] = d;
}
return w;
}
}
func compress(chars []byte) int {
w := 0
for i := 0; i < len(chars); {
j := i
for j < len(chars) && chars[j] == chars[i] {
j++
}
chars[w] = chars[i]
w++
if j-i > 1 {
for _, d := range strconv.Itoa(j - i) {
chars[w] = byte(d)
w++
}
}
i = j
}
return w
}