Start learning free

LESSON 19 OF 71 · PROJECTS: COMMAND-LINE TOOLS

uniq -d in Swift: Printing Only Repeated Lines

Practice Read the full explanation

Build a version of the Unix uniq -d command. Given a list of lines, output only the values whose adjacent run length is greater than one — i.e. lines that actually repeat back-to-back. Each surviving value is printed once (no count, just the value), joined by \n.

Function signature:

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

Example:

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

Output: "a\nc"

When printed:
a
c

The run of "a"s has length 2 and the run of "c"s has length 3, so both survive. The single "b" is dropped.


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

if count > 1 {
    result.append(prev)
}


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

STEP 1 OF 13
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Uniq V3 in Swift, explained

    Problem overview

    The third version of the uniq project adds the -d flag. The function uniqDups(_ lines: [String]) -> String outputs only the values whose adjacent run is longer than one line, that is, lines that actually repeat back to back. Each surviving value appears once, with no count, and the values are joined by \n.

    For ["a", "a", "b", "c", "c", "c"] the result is "a\nc". The run of a lines has length 2 and the run of c lines has length 3, so both survive. The single b is dropped. As in the earlier versions, only neighbours count: in ["a", "b", "a"] the two a lines are not adjacent, so nothing is repeated and the result is "".

    Approach

    The structure is the one from version 2. The loop keeps prev, the text of the current run, and count, its length so far. A run is judged when it ends, and the only change is the judgement: version 2 wrote every run with its count, while this version writes prev alone, and only when count is above 1.

    The same two traps apply. A run ends only when a different line arrives, so the last run is still open when the loop finishes and must be judged once more after the loop. And before the first line there is no run at all. Here the guard comes for free: at the start count is 0, which is not above 1, so nothing is written for the nonexistent run.

    Step by step

    1. Create result, an empty array of strings, with var. It will hold one copy of each line that repeated.
    2. Create count as a var starting at 0, meaning no run has started.
    3. Create prev as a var set to "", to remember the line the current run is made of.
    4. Loop over the positions with for i in 0..<lines.count, writing the closing brace right away.
    5. Test for a continuing run. Write if count > 0 && lines[i] == prev and its else. A run must exist and the line must match it.
    6. Extend the run in the if branch by adding 1 to count.
    7. Judge the finished run. In the else branch the old run is over. An inner if count > 1 is true only if that run was repeated.
    8. Record it once. Inside that if, append prev to result. One copy is enough, however long the run was.
    9. Start the next run by setting prev to lines[i], the line that ended the old run.
    10. Set count to 1 for the new run.
    11. Judge the open run. After the loop, repeat the test as if count > 1, outside the loop.
    12. Record it by appending prev to result, as in the loop.
    13. Join and return with result.joined(separator: "\n").

    The solution in Swift

        func uniqDups(_ lines: [String]) -> String {
            var result = [String]()
            var count = 0
            var prev = ""
            for i in 0..<lines.count {
                if count > 0 && lines[i] == prev {
                    count += 1
                } else {
                    if count > 1 {
                        result.append(prev)
                    }
                    prev = lines[i]
                    count = 1
                }
            }
            if count > 1 {
                result.append(prev)
            }
            return result.joined(separator: "\n")
        }
    

    The details a learner might trip on:

    • Two thresholds in one pattern. The same loop uses count > 0 to ask whether a run exists and count > 1 to ask whether it was repeated. Mixing them up, for example writing count > 0 in the inner test, would print every line, which is the behaviour of version 2 without the counts.
    • The continuing-run test spells out its meaning. count > 0 && lines[i] == prev reads as "a run is going and this line extends it". The starting value prev = "" is just a placeholder, and the guard on the write keeps it from ever being recorded as a run.
    • Values, not positions. The array holds the text of repeated lines. A run of five equal lines still adds just one entry.
    • Values, again. Equality uses == on strings, so case and trailing spaces matter: "a" and "a " are different lines and don't form a run.

    Complexity

    Time is O(n) in the total number of characters: each line is compared once with prev. Extra space is the array of repeated values and the joined string, at most proportional to the input.

    Edge cases and common mistakes

    • Forgetting the open run. ["b", "a", "a"] should give "a". Without the code after the loop, the final run of a lines is never judged and the result is "".
    • The same value in two runs. ["a", "a", "b", "a", "a"] returns "a\na". Each run is a separate repeat, so the value is printed once per run, not once overall.
    • Non-adjacent repeats. ["a", "b", "a"] returns "".
    • Two equal lines. ["x", "x"] returns "x": a run of length exactly 2 counts.
    • Empty input returns "".
    • Repeated blank lines. ["", "", "a"] returns "". The blank line did repeat, so it was recorded, but a single empty string joined with nothing is the empty string, so the result looks the same as when nothing repeated.

    Testing

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