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
- Create
result, an empty array of strings, withvar. It will hold one copy of each line that repeated. - Create
countas avarstarting at 0, meaning no run has started. - Create
prevas avarset to"", to remember the line the current run is made of. - Loop over the positions with
for i in 0..<lines.count, writing the closing brace right away. - Test for a continuing run. Write
if count > 0 && lines[i] == prevand itselse. A run must exist and the line must match it. - Extend the run in the
ifbranch by adding 1 tocount. - Judge the finished run. In the
elsebranch the old run is over. An innerif count > 1is true only if that run was repeated. - Record it once. Inside that
if, appendprevtoresult. One copy is enough, however long the run was. - Start the next run by setting
prevtolines[i], the line that ended the old run. - Set
countto 1 for the new run. - Judge the open run. After the loop, repeat the test as
if count > 1, outside the loop. - Record it by appending
prevtoresult, as in the loop. - 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 > 0to ask whether a run exists andcount > 1to ask whether it was repeated. Mixing them up, for example writingcount > 0in 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] == prevreads as "a run is going and this line extends it". The starting valueprev = ""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 ofalines 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
| lines | Result |
|---|---|
["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"] | "" |
[] | "" |
