Start learning free

LESSON 18 OF 69 · PROJECTS: COMMAND-LINE TOOLS

uniq -c in C#: Counting Runs with string.Format

Practice Read the full explanation

Build a version of the Unix uniq -c command. Given a list of lines, collapse each run of adjacent duplicates into a single output line that shows the run's count followed by the value.

Each output line is formatted as string.Format("{0,7} {1}", count, value): a 7-character right-aligned count, a single space, then the line value. Join all output lines with \n.

Function signature:

public string UniqCount(List<string> lines)

Example:

Input: lines = ["a", "a", "b", "c", "c", "c"]

Output (when printed):
      2 a
      1 b
      3 c

The first run is two "a"s, then a single "b", then three "c"s — three output lines.


Track string prev and int count. When a NEW value comes in (or you reach end), flush the previous run with string.Format("{0,7} {1}", count, prev) and reset.

Don't forget to flush AFTER the loop too. Use == for the string comparison.
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;
}


The full solution:
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);
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Uniq V2 in C#, explained

    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 prev and a run is going: the run grows, so add 1 to count.
    • 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

    1. Create result, an empty List<string> with one entry per run.
    2. Create count at 0. Zero means that no run has started.
    3. Create prev as null, meaning there is no text yet.
    4. Loop over the indexes with for, from 0 while i < lines.Count.
    5. Test whether the run continues: count > 0 and lines[i] == prev. Add the else branch right away.
    6. In the if branch, do count++.
    7. In the else branch, check for a finished run: an if on count > 0. At the first line no run exists yet, so nothing is written.
    8. Write the finished run into result with string.Format("{0,7} {1}", count, prev).
    9. Start the new run: set prev to lines[i].
    10. Set count to 1, since the new run has one line so far.
    11. After the loop, repeat the check count > 0, because the last run has not been written.
    12. Write it with the same string.Format call.
    13. 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 by 3, then comes the separating space from the format string, then c.
    • 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.
    • null for "no text yet". string is a reference type, so it can be null. The count > 0 check makes the code never rely on prev while it is null, and comparing a string with null with == is safe anyway, it is simply false.
    • 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 the a run, and b would be lost.
    • Empty list. The loop does not run, count stays 0, nothing is written, and the result is "".
    • Writing at the first line. Without the count > 0 check in the else branch, an entry for a run of 0 lines, with no text, would be added before the first real run.
    • Starting count at 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 "".
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free