Start learning free

LESSON 389 OF 413 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: uniq v2 — Count Adjacent Runs in C#

Practice

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

    Uniq V2 in C#

    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free