Problem overview
UniqCount is the -c flag of uniq. It takes a List<string> of lines and collapses each run of adjacent equal lines into one output line: the length of the run, right-aligned in 7 characters, then a space, then the line itself. The output lines are joined with \n.
For ["a", "a", "b", "c", "c", "c"] there are three runs: two as, one b and three cs. The result, printed, is:
2 a
1 b
3 c
Approach
The method has to remember the run it is in: which line it repeats (prev) and how many times it has been seen so far (count). For each new line there are two cases:
- The line equals
prevand a run is going: the run grows, so add 1 tocount. - Otherwise the old run has ended. Write its output line, if there was a run at all, then start a new run with the current line and a count of 1.
A run is only written when a different line arrives after it, so the very last run is never written inside the loop. It is still open when the loop ends, and a final write after the loop handles it. That final write is the part most often forgotten.
Tracing the example
With ["a", "a", "b", "c", "c", "c"]: the first a finds count at 0, so it starts a run (prev is "a", count is 1). The second a matches, so count becomes 2. The b differs, so the run 2 a is written and a new run b starts. The first c ends the b run (written as 1 b) and starts the c run, which grows to 3. The loop ends with that run still open, and the final write adds 3 c.
Step by step
- Create
result, an emptyList<string>with one entry per run. - Create
countat 0. Zero means that no run has started. - Create
prevasnull, meaning there is no text yet. - Loop over the indexes with
for, from 0 whilei < lines.Count. - Test whether the run continues:
count > 0andlines[i] == prev. Add theelsebranch right away. - In the
ifbranch, docount++. - In the
elsebranch, check for a finished run: anifoncount > 0. At the first line no run exists yet, so nothing is written. - Write the finished run into
resultwithstring.Format("{0,7} {1}", count, prev). - Start the new run: set
prevtolines[i]. - Set
countto 1, since the new run has one line so far. - After the loop, repeat the check
count > 0, because the last run has not been written. - Write it with the same
string.Formatcall. - Return
string.Join("\n", result).
The solution in C#
class Solution {
public string UniqCount(List<string> lines) {
List<string> result = new List<string>();
int count = 0;
string prev = null;
for (int i = 0; i < lines.Count; i++) {
if (count > 0 && lines[i] == prev) {
count++;
} else {
if (count > 0) {
result.Add(string.Format("{0,7} {1}", count, prev));
}
prev = lines[i];
count = 1;
}
}
if (count > 0) {
result.Add(string.Format("{0,7} {1}", count, prev));
}
return string.Join("\n", result);
}
}
The details worth knowing:
- The format string. In
"{0,7} {1}",{0,7}inserts the first argument padded on the left to a width of 7, and{1}inserts the second. With a count of 3 the first field is six spaces followed by3, then comes the separating space from the format string, thenc. - A wider number is not cut. A width is a minimum: the count 12345678 prints in full, and only shorter numbers are padded.
- A negative width pads on the right, as in
{0,-7}. The lesson needs the positive, right-aligned form. nullfor "no text yet".stringis a reference type, so it can benull. Thecount > 0check makes the code never rely onprevwhile it isnull, and comparing a string withnullwith==is safe anyway, it is simplyfalse.- The same expression twice. The line is built in the loop and after it, because the last run needs the same output. Both produce the same format.
Complexity
Let n be the number of lines. Time: one pass, with a string comparison and possibly a format call per line, so it grows linearly with n (times the line length). Space: the result has one string per run, at most n.
Edge cases and common mistakes
- Forgetting the final write. For
["a", "b"]the loop writes only thearun, andbwould be lost. - Empty list. The loop does not run,
countstays 0, nothing is written, and the result is"". - Writing at the first line. Without the
count > 0check in theelsebranch, an entry for a run of 0 lines, with no text, would be added before the first real run. - Starting
countat 0 for a new run. The new run already contains the line that ended the old one, so it starts at 1. - Non-adjacent repeats.
["a", "b", "a"]gives three runs of 1. - Empty lines.
["", "", "x"]gives a run of 2 for the empty line, printed as six spaces,2, a space and nothing.
Testing
["a", "a", "b", "c", "c", "c"]gives the three lines shown at the top.["x"]gives a single line: six spaces,1, a space,x.[]gives"".
