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 tocount. - It differs from
prev, so the previous run just ended and its final length is known. If that length is 1, saveprev. 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
- Create
resultas an empty[String]declared withvar, because the lone lines are appended to it. - Create
countstarting at 0. Zero means no run has started yet, which is true before the first line. - Create
prevas aString?set tonil. Before the first line there is no previous text, so the type has to be able to hold "nothing". - Loop over the positions
0..<lines.count. - Test whether the run continues. Two things must both hold: a run exists (
count > 0) andlines[i]equalsprev. Add theelsebranch at the same time. - In the
ifbranch, add 1 tocount. The run got one line longer. - In the
elsebranch, testcount == 1. A different line has arrived, so the run before it is over. On the very first line,countis 0, so nothing is saved. - Append
prev!toresultinside that test. The run stood alone. - Still in the
elsebranch, setprevtolines[i]. The line that ended the old run starts the new one. - Set
countto 1 for that new run. - After the loop, test
count == 1again. The last run is still open and nothing has judged it. - Append
prev!inside that second test, as in the loop. - 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
previs optional. AStringin Swift can never be missing, so "no line seen yet" needsString?. Comparinglines[i] == prevcompares aStringwith aString?. Swift wraps the left side in an optional for the comparison, and the result isfalsewhileprevisnil. - The
count > 0guard. The comparison is already false whileprevisnil, 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 ifprevisnil. Here that cannot happen, becausecountequals 1 only afterprevhas been assigned a line. That is why the check oncountcomes before everyprev!. ==on strings. It compares the text itself, not references, so two separateStringvalues with the same characters are equal.0..<lines.count. The half-open range excludeslines.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 emptyresultgives 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. Forgettingcount = 1in theelsebranch lets the next run inherit the old length. - Using
count > 1by 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"".
