Start learning free

LESSON 18 OF 71 · PROJECTS: COMMAND-LINE TOOLS

uniq -c in Swift: Counting Adjacent Runs with String(format:)

Practice Read the full explanation

Build a version of the Unix uniq -c command. Given a list of lines, collapse each run of adjacent duplicates into a single output line that shows the run's count followed by the value.

Each output line is formatted as String(format: "%7d ", count) + value: a 7-character right-aligned count, a single space, then the line value. Join all output lines with \n.

Function signature:

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

Example:

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

Output (when printed):
      2 a
      1 b
      3 c

The first run is two "a"s, then a single "b", then three "c"s — three output lines.


Track var prev and var count. When a NEW value comes in (or you reach end), flush the previous run with String(format: "%7d ", count) + prev and reset.

Don't forget to flush AFTER the loop too. Use == for the string comparison.
if count > 0 && lines[i] == prev {
    count += 1
} else {
    if count > 0 {
        result.append(String(format: "%7d ", count) + prev)
    }
    prev = lines[i]
    count = 1
}


The full solution:
class Solution {
    func uniqCount(_ 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 > 0 {
                    result.append(String(format: "%7d ", count) + prev)
                }
                prev = lines[i]
                count = 1
            }
        }
        if count > 0 {
            result.append(String(format: "%7d ", count) + prev)
        }
        return result.joined(separator: "\n")
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Uniq V2 in Swift, explained

    Problem overview

    The second version of the uniq project adds the -c flag. The function uniqCount(_ lines: [String]) -> String collapses each run of adjacent equal lines into one output line that shows the run's length followed by the value. Each output line is String(format: "%7d ", count) + value: the count right-aligned in 7 characters, one space, then the line itself. The output lines are joined with \n.

    For ["a", "a", "b", "c", "c", "c"] the runs are two a lines, one b and three c lines, so the output has three lines:

          2 a
          1 b
          3 c
    

    Version 1 only had to decide whether to keep a line. Now the function must remember how long the current run is, which takes two variables that describe the run in progress.

    Approach

    A run is written out when it ends, and it ends when a different line arrives. So the loop tracks the current run with two variables: prev, the text of the run, and count, how many lines it has so far. For each new line there are two cases:

    • If a run is going and the line equals prev, the run grows: add 1 to count.
    • Otherwise the old run is over. Write its output line, if there was a run, then start a new run with this line and a count of 1.

    Two details need care. Before the first line there is no run, which is why count starts at 0 and the inner test count > 0 guards the write: with no run yet, there is nothing to write. And the last run has no following line to end it, so the loop never writes it. After the loop, the same write has to happen once more.

    For the example, the state after each line is:

    After lineprevcountOutput lines written so far
    "a" (index 0)"a"10
    "a" (index 1)"a"20
    "b" (index 2)"b"11
    "c" (index 3)"c"12
    "c" (index 4)"c"22
    "c" (index 5)"c"32

    When the loop ends, the run of three c lines is still open with only two output lines written. The final write adds the third.

    Step by step

    1. Create result, an empty array of strings, with var. It will hold one output line per run.
    2. Create count as a var starting at 0. The value 0 means no run has started.
    3. Create prev as a var set to "". It will remember which 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, followed by its else. Both conditions must hold: a run exists, and this line matches it.
    6. Extend the run in the if branch by adding 1 to count.
    7. Detect a finished run. In the else branch a different line has arrived, so the run before it is over. An inner if count > 0 checks that a run was actually going, which is false only for the very first line.
    8. Write the finished run. Inside that inner if, append String(format: "%7d ", count) + prev to result. %7d is a whole number padded with spaces on the left to width 7, and the space after it is part of the format.
    9. Start the next run after the inner if: set prev to lines[i]. The line that ended the old run is the first line of the new one.
    10. Set count to 1 for the new run.
    11. Handle the open run. After the loop, write the same test, if count > 0. This one is outside the loop.
    12. Write the last run inside it, with the same format.
    13. Join and return with result.joined(separator: "\n").

    The solution in Swift

        func uniqCount(_ 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 > 0 {
                        result.append(String(format: "%7d ", count) + prev)
                    }
                    prev = lines[i]
                    count = 1
                }
            }
            if count > 0 {
                result.append(String(format: "%7d ", count) + prev)
            }
            return result.joined(separator: "\n")
        }
    

    The details a learner might trip on:

    • String(format:) comes from Foundation. It follows the printf style. %7d works with an Int argument, and String(format: "%7d ", 42) is five spaces, 42 and one trailing space. The separating space is part of the format string, so it sits before the value.
    • Width, not a limit. A count that needs more than 7 digits isn't cut: a run of 12,345,678 lines gives 12345678 z, with one space and no padding.
    • A blank first line is an ordinary value. With ["", "", "a"] the output is two runs: a run of 2 blank lines and a run of 1 a. The starting value prev = "" doesn't get in the way, because the guard in front of the write is count > 0, which is false until a run has started.
    • The else branch does two jobs. It closes the old run, which may not exist, and opens the new one. Both jobs belong there because a different line ends one run and begins another at once.

    Complexity

    Time is O(n) in the total number of characters: each line is compared once with prev, and each run is formatted once. Extra space is the array of output lines plus the joined string, which is at most proportional to the input size.

    Edge cases and common mistakes

    • Forgetting the last run. Without the code after the loop, the output for the example loses its c line and ends after b.
    • Empty input. [] gives "": the loop doesn't run, count is still 0 and the final write is skipped.
    • A single line. ["x"] gives " 1 x", six spaces and a 1, then a space and x.
    • Non-adjacent repeats are separate runs. ["a", "b", "a"] gives three output lines, each with a count of 1.
    • Blank lines are values. [""] gives " 1 ", the count, then a space, then nothing.
    • Wrong width. Using %d instead of %7d, or dropping the space after it, changes the text and the lesson's tests fail.

    Testing

    linesResult
    ["a", "a", "b", "c", "c", "c"]" 2 a\n 1 b\n 3 c"
    ["", "", "a"]" 2 \n 1 a"
    ["a", "b", "a"]" 1 a\n 1 b\n 1 a"
    ["x"]" 1 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