Start learning free

LESSON 17 OF 69 · PROJECTS: COMMAND-LINE TOOLS

uniq in C#: Dropping Adjacent Duplicate Lines

Practice Read the full explanation

Build a tiny version of the Unix uniq command. Given a list of lines, drop adjacent duplicate lines (keep only the first occurrence in each consecutive run) and return the surviving lines joined by newline characters (\n).

Function signature:

public string Uniq(List<string> lines)

Example:

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

Output: "a\nb\nc\na"

When printed:
a
b
c
a

Notice that the trailing "a" survives because it is not adjacent to the first run of "a"s — only consecutive duplicates are removed.


Build a List<string> result and add the current line only if result is empty or the line differs from result[result.Count - 1]. Then join the survivors with string.Join("\n", result).

if (result.Count == 0 || lines[i] != result[result.Count - 1]) {
    result.Add(lines[i]);
}


The full solution:
class Solution {
    public string Uniq(List<string> lines) {
        List<string> result = new List<string>();
        for (int i = 0; i < lines.Count; i++) {
            if (result.Count == 0 || lines[i] != result[result.Count - 1]) {
                result.Add(lines[i]);
            }
        }
        return string.Join("\n", result);
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Uniq V1 in C#, explained

    Problem overview

    Uniq takes a List<string> of lines and removes adjacent duplicates: in every run of equal consecutive lines, only the first is kept. The surviving lines are joined with \n and returned as one string.

    For ["a", "a", "b", "c", "c", "c", "a"] the result is "a\nb\nc\na". The last "a" stays because it is not next to the first run of "a": only neighbours are compared, so this is not the same as removing every repeated value.

    Approach

    Build the output as you go, and compare each incoming line with the last line you kept. If it differs, keep it. If it is the same, it belongs to a run that has already been represented, so skip it. Because you only ever compare with the last kept line, one pass through the list is enough, and nothing needs sorting or remembering beyond that.

    The first line has nothing before it. With an empty result there is no last item to compare with, so the code must treat that case separately and keep the line.

    Step by step

    1. Create result, an empty List<string> that collects the lines to keep. A list grows as lines are added, unlike an array.
    2. Loop with an index. Use for, with i from 0 while i < lines.Count, so that lines[i] is the current line.
    3. Decide whether to keep it. The condition is true when result is empty, or when lines[i] differs from result[result.Count - 1], the last kept line.
    4. Add the line to result with result.Add(lines[i]), only when the condition holds.
    5. Return the joined text with string.Join("\n", result).

    The solution in C#

    class Solution {
        public string Uniq(List<string> lines) {
            List<string> result = new List<string>();
            for (int i = 0; i < lines.Count; i++) {
                if (result.Count == 0 || lines[i] != result[result.Count - 1]) {
                    result.Add(lines[i]);
                }
            }
            return string.Join("\n", result);
        }
    }
    

    The details worth knowing:

    • The order of the two tests matters. || stops as soon as the left side is true. When result is empty, result.Count == 0 is true and the right side is never evaluated. Reversed, the code would read result[-1] on an empty list, which throws an ArgumentOutOfRangeException.
    • The last item is at Count - 1. Lists are indexed from 0, so a list of 3 items ends at index 2. Indexing with result.Count itself is out of range.
    • != compares string contents. Two strings with the same characters are equal, even if they are different objects, and the comparison is case-sensitive: "A" and "a" are different lines.
    • string.Join adds the separator only between items. There is no newline after the last line, and an empty list gives "".
    • Counting with Count. A List uses Count, while an array would use Length.

    Complexity

    Let n be the number of lines. Time: the loop runs n times, and each step compares two strings and may add to the list, so the work grows with n times the line length. Space: the result list holds up to n references to existing strings, plus the joined output.

    Edge cases and common mistakes

    • Empty list. The loop does not run and the result is "".
    • All lines equal. ["x", "x", "x"] gives "x".
    • Non-adjacent repeats. ["a", "b", "a"] gives "a\nb\na", with all three lines. Using a set of seen lines would wrongly drop the second "a".
    • Empty lines. Three empty strings are one run, and the result is a single empty string.
    • A trailing newline. Joining with += "\n" leaves one at the end, which the expected output does not have.

    Testing

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