Start learning free

LESSON 20 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Uniq V4 in C#: Keep Only Lines That Don't Repeat

Practice Read the full explanation

Build a version of the Unix uniq -u command. Given a list of lines, output only the values whose adjacent run length is exactly one — i.e. lines that did NOT repeat back-to-back. Surviving values are joined by \n.

Function signature:

string UniqOnce(List<string> lines)

Example:

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

Output: "b"

When printed:
b

The two "a"s and the three "c"s are dropped because their runs are longer than 1. Only the lone "b" survives.


Track prev and count. When the line changes (or after the loop), flush prev only if count == 1.

if (count == 1) {
    result.Add(prev);
}
In C#, == compares string values directly.

The full solution:
class Solution {
    public string UniqOnce(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 == 1) {
                    result.Add(prev);
                }
                prev = lines[i];
                count = 1;
            }
        }
        if (count == 1) {
            result.Add(prev);
        }
        return string.Join("\n", result);
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Uniq V4 in C#, explained

    Problem overview

    The method UniqOnce takes a List<string> of lines and imitates uniq -u. It returns one string holding every line that was not repeated right next to itself, with a newline between each two lines.

    The key word is adjacent. A line counts as repeated only when the same text appears in consecutive positions. For ["a", "a", "b", "c", "c", "c"] the runs are a a, b and c c c. Only the run of length 1 survives, so the result is "b". Note that a line which appears twice but in different places is not a repeat: ["a", "b", "a"] contains three runs of length 1, and all three lines are kept, giving "a\nb\na".

    Approach: measure each run as you walk past it

    The input is not sorted and we may not sort it, so we cannot count how often each text occurs overall. Instead, the method walks the list once and keeps two pieces of state that describe the current run:

    • prev, the text the run is made of;
    • count, how many lines the run has so far.

    When the next line equals prev, the run grows. When it differs, the run has ended, and at that moment we know its final length. If the length is exactly 1, the line goes into the result. Then the new line starts a new run.

    There is one subtle point: a run only ends when a different line arrives. The last run in the list has no line after it, so the loop never closes it. A second check after the loop handles that run.

    Step by step

    1. Create result, an empty List<string>. A list suits this job because its size is not known in advance and it grows with Add.
    2. Start count at 0. Zero means that no run has begun yet.
    3. Start prev as null, meaning no text so far.
    4. Loop over the positions from 0 while i < lines.Count. For a list the size is Count, not Length.
    5. Test whether the line continues the run: count > 0 && lines[i] == prev. Both parts matter. The first part says that a run exists, and the second says that this line matches it.
    6. If so, add 1 to count.
    7. Otherwise a different line has arrived, so the previous run is over. Check whether its count equals 1. On the very first line count is 0, so nothing is added.
    8. Add prev to result when that check is true: this run stood alone.
    9. Start the next run: set prev to lines[i],
    10. and set count to 1.
    11. After the loop, test count == 1 again. This handles the final run, which no later line closed.
    12. Add prev to result if it passed.
    13. Return string.Join("\n", result). The separator goes between two lines only, so there is no newline after the last one.

    The solution in C#

    class Solution {
        public string UniqOnce(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 == 1) {
                        result.Add(prev);
                    }
                    prev = lines[i];
                    count = 1;
                }
            }
            if (count == 1) {
                result.Add(prev);
            }
            return string.Join("\n", result);
        }
    }
    

    The C# details worth knowing:

    • == compares string contents. string is a reference type, but it overloads == to compare the characters, so lines[i] == prev is true for two separate string objects holding the same text.
    • null is a valid string. prev starts as null, and the count > 0 test states plainly that the first line always starts a run, instead of relying on a comparison with null.
    • List<T> versus arrays. result is a list because we don't know how many lines survive. An array has a fixed length from the moment it is created.
    • string.Join on an empty list returns the empty string "", so an empty input or an input where every line repeats needs no special case.

    Complexity

    Time: O(n). The loop visits each line once, and each visit does a constant amount of work apart from comparing two strings, which costs time proportional to their length. string.Join makes one more pass over the result.

    Space: O(n). In the worst case, no line repeats, so result holds all of them. Besides the list, the method uses two variables.

    Edge cases and common mistakes

    • Empty list. The loop never runs, count stays 0, and the result is "".
    • Single line. ["x"] becomes one run of length 1, which only the check after the loop adds. Without that check the answer would be wrongly empty.
    • Everything repeats. ["a", "a"] gives "".
    • Non-adjacent duplicates. ["a", "b", "a"] gives "a\nb\na". Using a counter dictionary over the whole list would drop both as, which is not what this command does.
    • Empty lines. An empty string is an ordinary line. ["", "", "x", ""] gives "x\n": the two empty lines at the start repeat and are dropped, x stays, and the final empty line is alone, so it stays too and leaves a trailing newline.
    • Forgetting to flush the last run. The loop only closes a run when a different line comes along.
    • Adding lines[i] instead of prev. When the run ends, lines[i] is the line that started the next run.

    Testing

    • ["a", "a", "b", "c", "c", "c"] gives "b".
    • [] gives "".
    • ["x"] gives "x".
    • ["a", "b", "a"] gives "a\nb\na".
    • ["a", "a"] 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