Problem overview
This version of the uniq project copies the -u flag. The function uniqOnce(lines: List<String>): String receives a list of lines and keeps only the lines that did not repeat right next to themselves. The survivors are joined with \n.
The word that matters is adjacent. uniq only compares a line with the line directly before it, so a repeat that is separated by something else doesn't count. With ["a", "a", "b", "c", "c", "c"] the input splits into three runs: a a, b and c c c. Only the run of length 1 survives, so the result is "b".
The previous version of the project already worked with runs of equal lines. This one changes what happens when a run ends: the run is printed only if its length is exactly 1.
Approach
You can't decide about a line when you first see it, because you don't yet know whether the next line equals it. So the code keeps a small memory of the run it is in:
prev, the line that makes up the current run;count, how many lines the run has so far.
For each new line, one of two things is true. Either it equals prev and the run grows, or it differs and the run is over. At that moment you know the run's final length, so you can decide: add prev to the result if count == 1, then start a new run with the new line. One pass over the list is enough, and nothing needs sorting or counting across the whole list.
Step by step
- Collect the answer. Create
result, an emptymutableListOf<String>(). It is avalbecause the list object never changes, only its contents. - Start the run counter.
countis avarstarting at 0. Zero means "no run has started yet". - Remember the run's line.
previs avarof typeString?, starting asnull. The?is needed because before the first line there is no previous text. - Visit every position with
for (i in 0 until lines.size). - Test for a continuing run. The condition is
count > 0 && lines[i] == prev: a run exists and this line repeats it. If so,count++. - Otherwise close the old run. In the
elsebranch, a different line has arrived. Ifcount == 1, the finished run stood alone, so addprev!!toresult. On the very first linecountis 0, so nothing is added. - Open the new run. Set
prev = lines[i]andcount = 1. - Flush the last run. After the loop the final run is still open, because no later line ended it. Repeat the same
if (count == 1)test there. - Join.
result.joinToString("\n")puts the separator between lines only, so the string has no trailing newline.
The solution in Kotlin
class Solution {
fun uniqOnce(lines: List<String>): String {
val result = mutableListOf<String>()
var count = 0
var prev: String? = null
for (i in 0 until lines.size) {
if (count > 0 && lines[i] == prev) {
count++
} else {
if (count == 1) {
result.add(prev!!)
}
prev = lines[i]
count = 1
}
}
if (count == 1) {
result.add(prev!!)
}
return result.joinToString("\n")
}
}
Kotlin details in this code
String?and!!.prevmay holdnull, so Kotlin refuses to pass it toresult.add, which needs a non-nullString. Writingprev!!tells the compiler "this isn't null here" and throws an exception if you are wrong. It is safe in both places becausecount == 1can only be true afterprevwas set.==compares contents. In Kotlinlines[i] == prevcallsequals, so two separateStringobjects with the same text are equal. It also works when one side isnull.===would compare references, which is not what you want here.0 until lines.sizestops beforelines.size, so the last valid index islines.size - 1. An empty list gives an empty range and the loop body never runs.
Tracing the example
Run on ["a", "a", "b", "c", "c", "c"], the code returns "b". Here is what the variables hold as each line is handled:
| Line | What happens | prev | count |
|---|---|---|---|
"a" | no run yet: start one | "a" | 1 |
"a" | repeats prev | "a" | 2 |
"b" | run of a had length 2: dropped, start a new run | "b" | 1 |
"c" | run of b had length 1: added, start a new run | "c" | 1 |
"c" | repeats | "c" | 2 |
"c" | repeats | "c" | 3 |
After the loop count is 3, so the final if adds nothing.
Complexity
The loop visits each line once and does constant work per line, so the time is O(n) for n lines, plus the cost of comparing strings, which is proportional to their length. The extra space is the result list, which holds at most n lines.
Edge cases and common mistakes
- Forgetting the last run. The loop only closes a run when a different line arrives. Without the check after the loop, a lone last line is lost. With
["x", "x", "y", "z", "z", "w"]the result isyandw;wcomes from the check after the loop. - Counting equal lines across the whole list. Only adjacent repeats count.
["a", "b", "a"]gives all three lines back, because no line touches an equal one. - Everything repeats.
["x", "x"]and the empty list both give the empty string"". - A single line.
["solo"]gives"solo", again thanks to the check after the loop. - Empty lines are lines. In
["", "a", "a", ""]the two empty strings are not adjacent, so both survive and the result is"\n": an empty line, a newline, and another empty line.
