Start learning free

LESSON 19 OF 70 · PROJECTS: COMMAND-LINE TOOLS

uniq -d in Kotlin: Printing Only Repeated Lines

Practice Read the full explanation

Build a version of the Unix uniq -d command. Given a list of lines, output only the values whose adjacent run length is greater than one — i.e. lines that actually repeat back-to-back. Each surviving value is printed once (no count, just the value), joined by \n.

Function signature:

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

Example:

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

Output: "a\nc"

When printed:
a
c

The run of "a"s has length 2 and the run of "c"s has length 3, so both survive. The single "b" is dropped.


Track prev and count. When the line changes (or after the loop), flush prev only if count > 1. Compare strings with ==, then join the survivors with joinToString("\n").

if (count > 1) {
    result.add(prev)
}


The full solution:
class Solution {
    fun uniqDups(lines: List<String>): String {
        val result = mutableListOf<String>()
        var count = 0
        var prev = ""
        for (i in lines.indices) {
            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 V3 in Kotlin, explained

    Problem overview

    This version builds the -d flag of uniq. The function uniqDups(lines: List<String>): String keeps only the values whose adjacent run is longer than one line, that is, lines that really repeat back to back. Each surviving value appears once, with no count, and the values are joined by \n.

    For lines = ["a", "a", "b", "c", "c", "c"] the result is "a\nc". The run of a has length 2 and the run of c has length 3, so both survive, and the single b is dropped. Printed:

    a
    c
    

    Approach: measure each run, keep the long ones

    The structure is the same as in the counting version: a variable prev for the text of the current run and a variable count for its length. A run is judged when it ends, that is, when a different line arrives. At that moment you know its final length, and if it is above 1, you add one copy of prev to the result.

    The last run has no following line to end it, so it must be judged again after the loop. The loop never tests it by itself.

    Because the test is count > 1 and not count > 0, you don't need to treat the first line specially. Before the first line, count is 0, which isn't above 1, so nothing is added for a run that doesn't exist. That also lets prev start as the plain empty string "" instead of a nullable type: its starting value is never added, because it is only used when count is above 1.

    Step by step

    1. Create the result list in a val named result. It holds one copy of each repeated line.
    2. Start the count at 0. A var named count is the length of the current run, and 0 means no run has started.
    3. Start prev as the empty string. A var named prev set to "" remembers the text of the current run.
    4. Loop by position with for (i in lines.indices), closing the brace right away.
    5. Continue or end the run. An if checks count > 0 && lines[i] == prev, with an else beside it.
    6. Extend the run. In the if branch, count++.
    7. Judge the finished run. In the else branch, a nested if checks count > 1: the run just ended was repeated. A run of one line isn't, and at the first line count is 0, which also fails the test.
    8. Keep one copy. Inside the nested if, result.add(prev). One copy is enough however long the run was.
    9. Start the next run. After the nested if, still in the else branch, set prev = lines[i].
    10. Give it a count of 1. count = 1.
    11. Judge the open run after the loop. Repeat the count > 1 check outside the loop.
    12. Keep its copy with result.add(prev), as inside the loop.
    13. Join and return with result.joinToString("\n").

    The solution in Kotlin

    class Solution {
        fun uniqDups(lines: List<String>): String {
            val result = mutableListOf<String>()
            var count = 0
            var prev = ""
            for (i in lines.indices) {
                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 to know:

    • var prev = "" infers the type String, so prev can never be null and needs no ?. The previous version used String? and null because it formats prev and wanted "no run yet" to be visible in the value. Here the count variable already says whether a run exists.
    • count > 0 && lines[i] == prev says in plain terms that a run must exist before a line can continue it. Since prev starts as "", the guard keeps the empty string from being mistaken for a real run before any line has been read, and the first line always goes through the else branch that starts a run.
    • && stops at the first false part, as || stops at the first true one.
    • joinToString("\n") returns "" for an empty list.

    Each repeated value is added when its run ends, so the output is in the same order as the runs appear in the input.

    Complexity

    The loop visits each line once, so the time is O(n) comparisons, and the result list holds at most one entry per run, so the extra space is O(n) in the worst case.

    Edge cases and common mistakes

    • Forgetting the last run. Without the final check, ["x", "x"] would give nothing, because the run is never ended by a different line.
    • Testing count > 0 instead of count > 1. That version keeps every run, which is the first version's output.
    • Non-adjacent repeats don't count. ["a", "a", "b", "a", "a"] has two separate runs of a, so a appears twice in the result. Neither run is merged with the other.
    • All lines different. ["a", "b", "c"] returns the empty string.
    • Repeated empty lines. ["", "", "x"] has a run of two empty lines, so one empty string is kept. The joined result is the empty string, which looks the same as having no result at all.
    • Printing every line of a run. Add prev once per run, not once per line.

    Testing

    These results come from running the reference solution:

    linesresult
    ["a", "a", "b", "c", "c", "c"]a and c, on two lines
    ["a", "a", "b", "a", "a"]a and a, on two lines
    ["x", "x"]x
    ["a", "b", "c"]the empty string
    []the empty string
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free