Problem overview
The method uniqCount(lines) is the -c flag of the Unix uniq command. It collapses every run of adjacent equal lines into one output line that shows how many times the line occurred. Each output line is the count padded on the left to 7 characters, then one space, then the value. The output lines are joined by "\n".
For ["a", "a", "b", "c", "c", "c"] there are three runs, so the result, printed, is:
2 a
1 b
3 c
The same text as a JavaScript string is " 2 a\n 1 b\n 3 c". An empty array gives "".
Approach: track the current run, write it when it ends
Now the function must remember something about the past: which line the current run is made of, and how long it is so far. Two variables hold that. prev is the run's line and count is its length; count being 0 means no run has started yet.
For each incoming line there are two cases. If a run is going and the line equals prev, the run grows: add 1 to count. Otherwise the line is different, so the previous run is over: write its output line (if there was a run at all), then start a new run with this line, with count set to 1.
A run is only written when a different line arrives. The very last run is never followed by a different line, so the loop leaves it unwritten. After the loop, one more check writes it. Forgetting this final flush is the classic bug of run-length code, and it silently drops the last group.
Step by step
- Create
resultas an empty array that will hold one output line per run. - Create
countat 0. Zero means "no run yet". - Create
prevasnull, meaning no value yet. It remembers the line the current run consists of. - Loop over the positions with
for (let i = 0; i < lines.length; i++). - Branch:
if (count > 0 && lines[i] === prev)continues a run, and itselsehandles everything else. Both conditions are needed: a run exists, and this line matches it. - In the
if, docount++. - In the
else, first checkcount > 0, because before the first line no run exists and nothing should be written. - Inside that check, push the finished run:
count.toString().padStart(7, ' ') + " " + prev. - Still in the
else, after the innerif, setprev = lines[i]: the line that ended the old run starts the new one. - Set
count = 1, since the new run has one line so far. - After the loop, test
count > 0again, because the last run is still open. - Push the last run with the same expression.
- Return
result.join("\n").
Tracing the example
For ["a", "a", "b", "c", "c", "c"], the state after each pass of the loop is:
| i | line | prev after | count after | output lines written so far |
|---|---|---|---|---|
| 0 | "a" | "a" | 1 | 0 |
| 1 | "a" | "a" | 2 | 0 |
| 2 | "b" | "b" | 1 | 1 |
| 3 | "c" | "c" | 1 | 2 |
| 4 | "c" | "c" | 2 | 2 |
| 5 | "c" | "c" | 3 | 2 |
Only two lines are written inside the loop, one when "b" arrives and one when the first "c" does. The run of "c" is still open when the loop ends, with count at 3, and the check after the loop writes it as the third line. That is why the final check is not optional.
The solution in JavaScript
class Solution {
uniqCount(lines) {
let result = [];
let count = 0;
let prev = null;
for (let i = 0; i < lines.length; i++) {
if (count > 0 && lines[i] === prev) {
count++;
} else {
if (count > 0) {
result.push(count.toString().padStart(7, ' ') + " " + prev);
}
prev = lines[i];
count = 1;
}
}
if (count > 0) {
result.push(count.toString().padStart(7, ' ') + " " + prev);
}
return result.join("\n");
}
}
Language details:
count.toString()turns the number into text, which is needed becausepadStartis a string method.padStart(7, ' ')adds spaces on the left until the string is 7 characters long, so"2"becomes six spaces and a 2.padStartnever cuts. A count with more than 7 digits, such as"12345678".padStart(7, " "), comes back unchanged at 8 characters.- Because the numbers are padded and then joined to
" "andprevwith+, the line value starts at the same column in every output line. - The code uses
===againstprev. Whenprevisnullthe left sidecount > 0is false first, so the comparison is skipped.
A common alternative is to compare lines[i] with lines[i - 1] and count backwards, but that needs special handling at index 0 and at the end too. Keeping prev and count as explicit state makes both boundaries visible in the code, which is easier to check.
Complexity
One pass visits each line once, comparing it with prev, so the time is proportional to the total text size. The result holds one string per run, so the extra space is at most proportional to the number of lines.
Edge cases and common mistakes
- Missing final flush. Without the check after the loop, the last run vanishes: the example would end after
b. - Writing a run for the first line. The
count > 0check in theelseprevents a bogus output line with count 0. - Non-adjacent repeats stay separate.
["a", "b", "a"]gives three runs, each with count 1. - Empty-string lines.
["", ""]is one run of 2 and gives" 2 ", with a trailing space after the count. - Empty input. The loop does not run and
countstays 0, so the result is"".
Testing
| lines | result |
|---|---|
["a", "a", "b", "c", "c", "c"] | " 2 a\n 1 b\n 3 c" |
["a", "b", "a"] | " 1 a\n 1 b\n 1 a" |
["", ""] | " 2 " |
[] | "" |
