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
- Create an empty array of strings named
resultwithvar, since it grows as lines are kept. - Loop over the positions with
for i in 0..<lines.count. The loop uses an index, because each pass looks atlines[i]directly. The closing brace goes in right away. - Test whether the line starts a new run. Write an
ifthat is true whenresultis empty, or whenlines[i]differs from the last item ofresult,result[result.count - 1]. Put the emptiness check first. - Keep the line. Inside the
if, appendlines[i]toresult. A line that equals the one kept just before it never gets here. - 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 evaluatesbonly whenaisfalse. So whenresultis empty, the right-hand side, which would indexresult[-1], never runs. Swapping the two conditions would crash on the first line. - Half-open range.
0..<lines.countstops beforelines.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
resultkeeps the code short. - Strings compare by content.
!=on twoStringvalues 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, thenx, 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.isEmptycrashes on the first line, because of the index out of range.
Testing
| lines | Result |
|---|---|
["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" |
[] | "" |
