Start learning free

LESSON 17 OF 71 · PROJECTS: COMMAND-LINE TOOLS

uniq in Swift: 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:

func uniq(_ lines: [String]) -> String

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 [String] result and append the current line only if result is empty or the line differs from result[result.count - 1]. Then join the survivors with joined(separator: "\n").

if result.isEmpty || lines[i] != result[result.count - 1] {
    result.append(lines[i])
}


The full solution:
class Solution {
    func uniq(_ lines: [String]) -> String {
        var result = [String]()
        for i in 0..<lines.count {
            if result.isEmpty || lines[i] != result[result.count - 1] {
                result.append(lines[i])
            }
        }
        return result.joined(separator: "\n")
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Uniq V1 in Swift, explained

    Problem overview

    This lesson builds a tiny version of the Unix uniq command. The function uniq(_ lines: [String]) -> String receives an array of lines, removes adjacent duplicates, keeping only the first line of each consecutive run, and returns the survivors joined by newline characters.

    For ["a", "a", "b", "c", "c", "c", "a"] the result is "a\nb\nc\na". The trailing "a" survives, because it isn't adjacent to the first run of "a" lines. Only consecutive duplicates are removed, so this is not the same as keeping each distinct value once.

    Approach

    Because only neighbours matter, there is no need for a set of lines already seen. It is enough to compare each line with the last line that was kept. If they differ, the line starts a new run and is kept. If they are equal, the line is a repeat of the run in progress and is skipped.

    The first line is the one special case: nothing has been kept yet, so there is no last line to compare with. Checking result.isEmpty first handles it, and it also keeps the code from reading the last item of an empty array, which would crash.

    The output is built the same way as in the grep lessons: collect the kept lines in an array and join them at the end, so the separator goes between lines and not after the last one.

    Step by step

    1. Create an empty array of strings named result with var, since it grows as lines are kept.
    2. Loop over the positions with for i in 0..<lines.count. The loop uses an index, because each pass looks at lines[i] directly. The closing brace goes in right away.
    3. Test whether the line starts a new run. Write an if that is true when result is empty, or when lines[i] differs from the last item of result, result[result.count - 1]. Put the emptiness check first.
    4. Keep the line. Inside the if, append lines[i] to result. A line that equals the one kept just before it never gets here.
    5. Join and return. After the loop, return result.joined(separator: "\n").

    The solution in Swift

        func uniq(_ lines: [String]) -> String {
            var result = [String]()
            for i in 0..<lines.count {
                if result.isEmpty || lines[i] != result[result.count - 1] {
                    result.append(lines[i])
                }
            }
            return result.joined(separator: "\n")
        }
    

    The details a learner might trip on:

    • Short-circuit evaluation. In a || b, Swift evaluates b only when a is false. So when result is empty, the right-hand side, which would index result[-1], never runs. Swapping the two conditions would crash on the first line.
    • Half-open range. 0..<lines.count stops before lines.count, so the last valid index is included and nothing past it. For an empty array the range is empty and the loop doesn't run.
    • Comparing with the last kept line, not the previous input line. They are the same thing here, because a skipped line equals the last kept one. Comparing with result keeps the code short.
    • Strings compare by content. != on two String values compares their characters, and it is case-sensitive, so "A" and "a" are different lines.

    Complexity

    The loop visits each line once and each comparison costs time proportional to the line length, so the time is O(n) in the total number of characters. Extra space is O(n) for the kept lines and the joined string. Reading the last item of an array is constant time.

    Edge cases and common mistakes

    • Non-adjacent repeats stay. ["p", "q", "p", "q"] returns "p\nq\np\nq", because no two equal lines are neighbours.
    • Empty input. [] returns "". A single blank line [""] also returns "", since the one kept line is the empty string and there is nothing to join it with. Both inputs give the same text, although the first has no lines and the second has one.
    • Blank lines are lines. ["", "", "x", "", ""] collapses to "\nx\n": a blank line, then x, then another blank line.
    • Case and spaces matter. ["A", "a", "a "] keeps all three, since "A", "a" and "a " are all different strings.
    • Checking emptiness second. Writing the condition as lines[i] != result[result.count - 1] || result.isEmpty crashes on the first line, because of the index out of range.

    Testing

    linesResult
    ["a", "a", "b", "c", "c", "c", "a"]"a\nb\nc\na"
    ["p", "q", "p", "q"]"p\nq\np\nq"
    ["", "", "x", "", ""]"\nx\n"
    ["A", "a", "a "]"A\na\na "
    ["x"]"x"
    []""
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free