Start learning free

LESSON 20 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Uniq -u in Kotlin: Keep Only the Loners

Practice Read the full explanation

Build a version of the Unix uniq -u command. Given a list of lines, output only the values whose adjacent run length is exactly one — i.e. lines that did NOT repeat back-to-back. Surviving values are joined by \n.

Function signature:

fun uniqOnce(lines: List<String>): String

Example:

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

Output: "b"

When printed:
b

The two "a"s and the three "c"s are dropped because their runs are longer than 1. Only the lone "b" survives.


Track prev and count. When the line changes (or after the loop), flush prev only if count == 1.

if (count == 1) {
    result.add(prev!!)
}
In Kotlin, == compares string values directly.

The full solution:
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")
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Uniq V4 in Kotlin, explained

    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

    1. Collect the answer. Create result, an empty mutableListOf<String>(). It is a val because the list object never changes, only its contents.
    2. Start the run counter. count is a var starting at 0. Zero means "no run has started yet".
    3. Remember the run's line. prev is a var of type String?, starting as null. The ? is needed because before the first line there is no previous text.
    4. Visit every position with for (i in 0 until lines.size).
    5. Test for a continuing run. The condition is count > 0 && lines[i] == prev: a run exists and this line repeats it. If so, count++.
    6. Otherwise close the old run. In the else branch, a different line has arrived. If count == 1, the finished run stood alone, so add prev!! to result. On the very first line count is 0, so nothing is added.
    7. Open the new run. Set prev = lines[i] and count = 1.
    8. 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.
    9. 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 !!. prev may hold null, so Kotlin refuses to pass it to result.add, which needs a non-null String. Writing prev!! tells the compiler "this isn't null here" and throws an exception if you are wrong. It is safe in both places because count == 1 can only be true after prev was set.
    • == compares contents. In Kotlin lines[i] == prev calls equals, so two separate String objects with the same text are equal. It also works when one side is null. === would compare references, which is not what you want here.
    • 0 until lines.size stops before lines.size, so the last valid index is lines.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:

    LineWhat happensprevcount
    "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 is y and w; w comes 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.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free