Start learning free

LESSON 17 OF 70 · PROJECTS: COMMAND-LINE TOOLS

uniq in Kotlin: Dropping Adjacent Duplicate Lines

Practice Read the full explanation

Build a tiny version of the Unix uniq command. Given a list of lines, drop adjacent duplicate lines (keep only the first occurrence in each consecutive run) and return the surviving lines joined by newline characters (\n).

Function signature:

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

Example:

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

Output: "a\nb\nc\na"

When printed:
a
b
c
a

Notice that the trailing "a" survives because it is not adjacent to the first run of "a"s — only consecutive duplicates are removed.


Build a MutableList<String> result and add the current line only if result is empty or the line differs from result[result.size - 1]. Then join the survivors with result.joinToString("\n").

if (result.isEmpty() || lines[i] != result[result.size - 1]) {
    result.add(lines[i])
}


The full solution:
class Solution {
    fun uniq(lines: List<String>): String {
        val result = mutableListOf<String>()
        for (i in lines.indices) {
            if (result.isEmpty() || lines[i] != result[result.size - 1]) {
                result.add(lines[i])
            }
        }
        return result.joinToString("\n")
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Uniq V1 in Kotlin, explained

    Problem overview

    This is the first version of a small uniq. The function uniq(lines: List<String>): String removes adjacent duplicate lines: in each run of equal consecutive lines only the first is kept. The surviving lines are returned joined by newline characters.

    With lines = ["a", "a", "b", "c", "c", "c", "a"] the result is "a\nb\nc\na". Printed:

    a
    b
    c
    a
    

    The last a survives. It equals the first line, but it isn't next to it, and uniq only compares neighbours. Removing every repeat anywhere in the list is a different task that needs a set or a sorted list.

    Approach: compare with the last line you kept

    You walk through the lines in order and keep a line only if it differs from the line you kept just before it. The last kept line is the last item of the result list, so the list doubles as the memory you need. If a line equals that last item, it belongs to a run you've already recorded, and you skip it.

    There is one special case. At the very first line the result is empty, so there is no last item to compare with, and the first line must be kept unconditionally. Asking "is the result empty?" first, and only then comparing, handles it.

    Step by step

    1. Create the result list. mutableListOf<String>() goes in a val named result. It holds the lines to keep.
    2. Loop by position. for (i in lines.indices) gives i every position from 0 to the last. lines[i] is the line at that position. Close the brace right away.
    3. Decide whether to keep the line. The if is true when result is empty, or when lines[i] differs from the last item of result, result[result.size - 1]. The empty check comes first so the second half never looks for an item that doesn't exist.
    4. Add the line. result.add(lines[i]) inside the if. A line equal to the one kept just before it never gets here.
    5. Join and return. result.joinToString("\n") puts a newline between each two lines, and none after the last.

    The solution in Kotlin

    class Solution {
        fun uniq(lines: List<String>): String {
            val result = mutableListOf<String>()
            for (i in lines.indices) {
                if (result.isEmpty() || lines[i] != result[result.size - 1]) {
                    result.add(lines[i])
                }
            }
            return result.joinToString("\n")
        }
    }
    

    Kotlin details to know:

    • || short-circuits. When result.isEmpty() is true, Kotlin doesn't evaluate the right side. That is what protects result[result.size - 1] from being read on an empty list, where index -1 would throw an exception.
    • != compares the contents of two strings, because it is the negation of ==, which calls equals. You don't need a special method for string comparison.
    • lines.indices is the range 0..lines.size - 1. For an empty list it is empty, so the loop body never runs.
    • result.last() would read the last item too, and is the more idiomatic way, but the lesson spells out the index to show what "last" means.

    Complexity

    The loop visits each line once, and each visit does a constant amount of work apart from comparing two strings, so the time is proportional to the number of lines, O(n), times the cost of comparing their text. The result list holds up to n lines, so the extra space is O(n).

    Edge cases and common mistakes

    • Empty input. No lines give an empty result and the empty string.
    • A single line. It is kept: ["x"] gives x.
    • Empty lines are lines too. ["", "", "a"] keeps one empty line and then a, so the result is a newline followed by a.
    • Non-adjacent repeats stay. ["b", "a", "b"] comes back whole.
    • Comparing in the wrong order. If the comparison ran before the emptiness check, the first line would crash the function with an index error.
    • Comparing with the previous input line instead of the last kept one. For this task the two are always equal in value, so either works, but the last kept item is the one the lesson uses, and it needs no extra variable.

    Testing

    These results come from running the reference solution:

    linesresult
    ["a", "a", "b", "c", "c", "c", "a"]a, b, c, a, on four lines
    ["", "", "a"]an empty line, then a
    ["b", "a", "b"]b, a, b, on three lines
    []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