Start learning free

LESSON 20 OF 71 · PROJECTS: COMMAND-LINE TOOLS

Uniq V4 in Swift: Keeping Only Lines That Never 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:

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

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.append(prev!)
}
In Swift, == compares string values directly.

The full solution:
class Solution {
    func uniqOnce(_ lines: [String]) -> String {
        var result = [String]()
        var count = 0
        var prev: String? = nil
        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 V4 in Swift, explained

    Problem overview

    This version of the uniq tool behaves like uniq -u. The method uniqOnce(_ lines: [String]) -> String receives a list of lines and keeps only the lines that were not repeated right next to themselves. The survivors are joined with "\n" into one string.

    The word that matters is adjacent. Only back-to-back repeats count. With ["a", "a", "b", "c", "c", "c"] the run of two "a" lines and the run of three "c" lines are dropped, and the lone "b" stays. The result is "b". With ["a", "b", "a"] nothing is dropped, because the two "a" lines are separated by a "b". Each of the three lines is a run of length 1, and the result is "a\nb\na".

    Approach: measure each run as you walk the list

    A run is a stretch of equal, neighbouring lines. A line survives exactly when its run has length 1. You can find the run lengths in a single pass, with no sorting and no dictionary. Keep two pieces of state: prev, the text of the run you are in, and count, how many lines that run has so far.

    For each new line, one of two things happens:

    • It equals prev, so the run grew. Add 1 to count.
    • It differs from prev, so the previous run just ended and its final length is known. If that length is 1, save prev. Then the new line starts a fresh run with a count of 1.

    The loop only learns that a run has ended when a different line arrives. The last run never gets such a line after it, so it needs one more check after the loop. This is the part learners forget most often.

    The previous version of the tool already walked a list of lines and compared neighbours. This version adds the run counter and the filter on count == 1. The next version builds on this one.

    Step by step

    1. Create result as an empty [String] declared with var, because the lone lines are appended to it.
    2. Create count starting at 0. Zero means no run has started yet, which is true before the first line.
    3. Create prev as a String? set to nil. Before the first line there is no previous text, so the type has to be able to hold "nothing".
    4. Loop over the positions 0..<lines.count.
    5. Test whether the run continues. Two things must both hold: a run exists (count > 0) and lines[i] equals prev. Add the else branch at the same time.
    6. In the if branch, add 1 to count. The run got one line longer.
    7. In the else branch, test count == 1. A different line has arrived, so the run before it is over. On the very first line, count is 0, so nothing is saved.
    8. Append prev! to result inside that test. The run stood alone.
    9. Still in the else branch, set prev to lines[i]. The line that ended the old run starts the new one.
    10. Set count to 1 for that new run.
    11. After the loop, test count == 1 again. The last run is still open and nothing has judged it.
    12. Append prev! inside that second test, as in the loop.
    13. Return result.joined(separator: "\n"). The separator goes between the lines, so the output has no trailing newline.

    The solution in Swift

    class Solution {
        func uniqOnce(_ lines: [String]) -> String {
            var result = [String]()
            var count = 0
            var prev: String? = nil
            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 Swift details worth a closer look:

    • Why prev is optional. A String in Swift can never be missing, so "no line seen yet" needs String?. Comparing lines[i] == prev compares a String with a String?. Swift wraps the left side in an optional for the comparison, and the result is false while prev is nil.
    • The count > 0 guard. The comparison is already false while prev is nil, so the guard states the intent more than it is required. It makes the code say: a run must exist before a line can continue it.
    • Force-unwrapping with !. prev! crashes the program if prev is nil. Here that cannot happen, because count equals 1 only after prev has been assigned a line. That is why the check on count comes before every prev!.
    • == on strings. It compares the text itself, not references, so two separate String values with the same characters are equal.
    • 0..<lines.count. The half-open range excludes lines.count, which is exactly the last valid index plus one. For an empty array the range is empty and the loop body never runs.
    • joined(separator:). It puts the separator between elements only. An empty result gives the empty string.

    Complexity

    Time: O(n) string comparisons for n lines. The loop visits each line once and does a constant amount of bookkeeping per line, apart from the cost of comparing two lines, which depends on their length. Space: O(n) in the worst case, when every line is a lone line and result holds all of them. Besides result, the function uses two variables.

    Edge cases and common mistakes

    • Forgetting the final run. For ["a", "b", "b"] the loop ends while the run of "b" lines is open. For ["x"] the loop never sees a different line at all. Without the check after the loop, a lone last line would be lost.
    • Treating non-adjacent repeats as repeats. The list ["a", "b", "a"] returns "a\nb\na". A set of seen lines would wrongly drop both "a" lines.
    • Dropping one copy instead of all. A run of two is dropped entirely, not reduced to one line. ["a", "a"] gives the empty string.
    • Empty lines are lines. ["", "", "z"] gives "z": the two empty strings form a run of 2. A lone empty line would stay and show up as an empty entry in the output.
    • Not resetting count. Forgetting count = 1 in the else branch lets the next run inherit the old length.
    • Using count > 1 by mistake. That keeps repeated runs, which is the opposite of what this tool does.

    Testing

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