Problem overview
The function uniqCount takes a vector<string> of lines and collapses each run of adjacent identical lines into one output line. That line shows the run's length and then the value, formatted like "%7d %s": the count right-aligned in 7 characters, one space, then the text. The output lines are joined with newlines. The previous version kept one line per run; this one also counts them.
For ["a", "a", "b", "c", "c", "c"] the result is:
2 a
1 b
3 c
As one string it is " 2 a\n 1 b\n 3 c". A count of 2 is padded with 6 spaces to fill 7 characters, then comes a space and the value.
Approach: track the current run and write it when it ends
The function walks through the lines while remembering the run it is in, using two variables. prev is the text of the current run, and count is how many lines it has so far. A count of 0 means that no run has started yet.
For each line there are two cases. If a run is going and the line equals prev, the run continues and count grows by 1. Otherwise the line starts a new run, which means the old run just ended. If there was an old run (count > 0), its output line is formatted and stored. Then prev becomes the new line and count becomes 1.
A run is written only when a different line arrives, so the last run of the input is never written inside the loop: no line comes after it. After the loop, the same test, count > 0, writes it. This also handles the empty input, where count is still 0 and nothing is written.
The finished lines are collected in a vector<string> and joined with newlines in a final loop, as in the first version.
Step by step
- Create an empty
vector<string>namedresultthat will hold one output line per run. - Create
int count = 0. It counts the lines of the current run; 0 means no run yet. - Create
string prev = "", the text of the current run. - Loop over the lines with
ifrom 0 whilei < lines.size(). - Test
count > 0 && lines[i] == prev. Both parts must hold to continue a run: one exists, and this line repeats it. Anelsebranch follows. - In the
ifbranch, docount++. The run got one line longer. - In the
elsebranch, testcount > 0. The branch means the old run ended, but before the first line there was no run, so the first line must not write anything. - Declare
char buf[32]inside thatif, a character buffer forsprintfto fill. - Call
sprintf(buf, "%7d ", count).%7dwrites the integer padded with spaces on the left up to width 7, and the space after it is part of the format. - Store the run's line with
result.push_back(string(buf) + prev). The buffer holds only the count part, soprevhas to follow it. - Still in the
else, after the innerif, setprev = lines[i]. The line that ended the old run starts the new one. - Set
count = 1. The new run has one line so far. - After the loop, repeat the write for the last run. An
if (count > 0)with a newbuf, the samesprintfand the samepush_back. - Join the lines. Create an empty
string out, loop overresult, add"\n"wheni > 0, and addresult[i]. - Return
out.
The solution in C++
class Solution {
public:
string uniqCount(vector<string> lines) {
vector<string> result;
int count = 0;
string prev = "";
for (int i = 0; i < lines.size(); i++) {
if (count > 0 && lines[i] == prev) {
count++;
} else {
if (count > 0) {
char buf[32];
sprintf(buf, "%7d ", count);
result.push_back(string(buf) + prev);
}
prev = lines[i];
count = 1;
}
}
if (count > 0) {
char buf[32];
sprintf(buf, "%7d ", count);
result.push_back(string(buf) + prev);
}
string out;
for (int i = 0; i < result.size(); i++) {
if (i > 0) out += "\n";
out += result[i];
}
return out;
}
};
The C++ details worth a closer look:
sprintfwrites into a character array. It comes from<cstdio>and uses C-style format strings. It does not check the size of the buffer, so the buffer must be large enough. Aninthas at most 11 characters with its sign, and with the padding and the space the text stays well below 32.- The width is a minimum.
%7dpads short numbers but never cuts a long one: a count with more than 7 digits would print in full and push the text to the right. string(buf) + prev. The character array is turned into astringfirst, because adding two C-style strings with+is not allowed. The text inbufends with a space, so the value follows after a single space.- The count guard handles blank lines.
prevstarts as an empty string, and an empty string can also be a real line. The test usescount > 0and not "prev is empty", so a run of empty lines is counted like any other. - The same code appears twice. The formatting inside the loop and the one after it are identical. Larger programs would move them into a helper function; here the repetition makes each step easy to see.
Complexity
Time: O(total length). Each line is compared with prev once, each run is formatted once, and the lines are joined in one pass.
Space: O(total length). The result vector and the output string hold the text of one line per run, plus the counts. The by-value parameter also copies the input.
Edge cases and common mistakes
- Empty input.
[]gives"": the loop doesn't run, andcountis 0 after it, so nothing is written. - A single line.
["x"]gives" 1 x". Its run is only written by the check after the loop. - Forgetting the last run. Without the check after the loop, the last run is dropped from every result.
- Runs of blank lines.
["", "", "a"]gives" 2 \n 1 a". The first output line is the count, a space and an empty value, so it ends with that space. - Separate runs of the same text.
["a", "b", "a"]gives" 1 a\n 1 b\n 1 a". The two"a"s are not adjacent, so they are two runs of 1. - Starting
countat 1. Then the first line would write a run withprevequal to the empty string before any real run existed. Starting at 0 and guarding withcount > 0avoids that. - Resetting
countto 0. In theelsebranch the new line is already the first line of the next run, socountbecomes 1. - Wrong padding. The format is
"%7d ": 7 characters for the number, then a space. Padding to 8 or leaving out the space gives lines that look similar but fail the tests.
Testing
["a", "a", "b", "c", "c", "c"]gives" 2 a\n 1 b\n 3 c".["x"]gives" 1 x".["", "", "a"]gives" 2 \n 1 a".["a", "b", "a"]gives" 1 a\n 1 b\n 1 a".[]gives"".
