1. Auxiliary String Buffer
Intuition
Iterate through chars, counting contiguous runs. Append character and count (if > 1) to a temporary string or list. Copy the characters back into chars and return the new length.
When to apply: Basic conceptual implementation.
Algorithm
- Initialize
res = []. - Loop
ifrom 0 ton - 1: -
char = chars[i],count = 0. - While
i < n && chars[i] == char:count++,i++. -
res.push(char). - If
count > 1: push each digit ofcounttores. - Copy
resintochars. - Return
res.length.
Auxiliary String Buffer
2 of 2 questions left todayObservation: First run consists of 'a' from index 0 to 1 (length 2)
Observation: First run consists of 'a' from index 0 to 1 (length 2).
Decision: Append character 'a' followed by count string '2' to auxiliary string buffer: buffer = 'a2'.
Invariant: Runs of length > 1 append their decimal digit count.
#include <iostream>#include <vector>#include <string> class Solution {public: int compress(std::vector<char>& chars) { std::vector<char> res; int n = chars.size(), i = 0; while (i < n) { char c = chars[i]; int count = 0; while (i < n && chars[i] == c) { count++; i++; } res.push_back(c); if (count > 1) { for (char digit : std::to_string(count)) { res.push_back(digit); } } } for (size_t k = 0; k < res.size(); ++k) { chars[k] = res[k]; } return res.size(); }}; int main() { Solution sol; std::vector<char> chars = {'a','a','b','b','c','c','c'}; int len = sol.compress(chars); std::cout << len << std::endl; // 6 return 0;}Time & Space Complexity
- Time complexity:
O(N)— Allocates an auxiliary array of size up to N. - Space complexity:
O(N)
Why Brute Force Doesn't Scale:
In-place write pointer eliminates intermediate array allocation.
Strict O(1) space complexity.