Problem overview
This version builds uniq -c. uniqCount(lines: string[]): string collapses each run of adjacent equal lines into one output line that shows the run's length and then the value. Each output line is count.toString().padStart(7, " ") + " " + value: the count right-aligned in 7 characters, one space, and the value. The output lines are joined with \n.
For ["a", "a", "b", "c", "c", "c"] the result printed is:
2 a
1 b
3 c
There are three runs: two "a"s, one "b" and three "c"s.
Approach: remember the current run
The previous version could decide about a line as soon as it saw it. Here a line can only be written once the run has ended, because only then is the count known. So the loop keeps two variables describing the run in progress: prev, the value of the run, and count, how many lines it has so far. A line equal to prev extends the run. A different line closes it: write the finished run, then start a new one with this line.
That leaves one run that nobody closes. The last run never meets a different line after it, so the loop ends with its data still in prev and count. After the loop, the same writing code runs once more for it.
Step by step
result: an emptystring[]that will hold one output line per run.count: a number starting at 0. Zero means no run has started yet.prev: typedstring | nulland set tonull, meaning "no line yet". It holds the value of the current run.- Loop by position with
ifrom 0 whilei < lines.length. - Same run or not. The
ifis true whencount > 0andlines[i] === prev. Both must hold: a run exists, and this line equals it. Theelsehandles everything else. - Extend the run. In the
ifbranch,count++. - Was a run going? In the
elsebranch, a different line has arrived, so the previous run is over, if there was one. Before the very first linecountis 0, so nothing is written. - Write the finished run. Push
count.toString().padStart(7, " ") + " " + prev.toString()makes the number into text, andpadStart(7, " ")adds spaces on its left until it is 7 characters long. - Start the next run. Still in the
else, setprev = lines[i]. - Count it as one. Set
count = 1. - After the loop, test again whether a run is open:
count > 0. - Write the last run inside that
if, with the same expression as before. - Join and return with
result.join("\n").
Tracing the example
These are the values after each iteration for ["a", "a", "b", "c", "c", "c"], together with the number of output lines pushed so far:
| i | line | count | prev | pushed |
|---|---|---|---|---|
| 0 | a | 1 | a | 0 |
| 1 | a | 2 | a | 0 |
| 2 | b | 1 | b | 1 |
| 3 | c | 1 | c | 2 |
| 4 | c | 2 | c | 2 |
| 5 | c | 3 | c | 2 |
After the loop two lines have been pushed, and count is still 3. The final if pushes the third line for the run of "c"s.
Notice that the else branch does two jobs in a fixed order: first it writes the old run, using prev and count, and only then does it overwrite them with the new line. Swapping the two would write the new line with the old count. The same order is what lets the first line work: with count at 0 the writing is skipped, and the run simply starts.
The solution in TypeScript
class Solution {
uniqCount(lines: string[]): string {
let result: string[] = [];
let count: number = 0;
let prev: string | null = 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:
string | nullis a union type:previs either text ornull. When it is concatenated into a string, anullwould turn into the text"null":"1 " + nullgives"1 null". The code never reaches that case, becausecountis above 0 only afterprevhas been set to a line.padStart(7, " ")never cuts a longer string:"12345678".padStart(7, " ")stays at 8 characters. A count of 12 gives" 12", which is 5 spaces and 2 digits.padStartbelongs to strings, so a number has to be converted first. Calling it on a number is reported by the compiler ("Property 'padStart' does not exist on type 'number'") and fails at run time with "n.padStart is not a function".count++adds one to the variable in place.
Complexity
One pass over the lines does constant work per line apart from comparing strings, so the time is O(n) in the total size of the input. The result holds one string per run, so the extra space is O(n) in the worst case, when every line differs from its neighbour.
Edge cases and common mistakes
- Forgetting the last run. Without the block after the loop, the last group is never written. For the example the output would stop after the
bline. - Writing at the start. The
count > 0test in theelseprevents a bogus line, with a count of 0 and anullvalue, from being pushed for the first line. - Empty input.
[]gives"", because bothcount > 0tests fail. - Single line.
["x"]gives" 1 x": six spaces, then the digit. - Non-adjacent repeats.
["a", "b", "a"]gives three separate lines, each with a count of 1, because the runs are not neighbours. - Case.
["a", "A"]are two runs of one.
Testing
| lines | Result |
|---|---|
[] | "" |
["x"] | " 1 x" |
["a", "b", "a"] | " 1 a\n 1 b\n 1 a" |
twelve copies of "z" | " 12 z" |
The next version builds on this one.
