Start learning free

LESSON 390 OF 415 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: uniq v1 — Drop Adjacent Duplicates in Swift

Practice

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

    Uniq V1 in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free