Start learning free

LESSON 18 OF 70 · PROJECTS: COMMAND-LINE TOOLS

uniq -c in Kotlin: Counting Adjacent Runs

Practice Read the full explanation

Build a version of the Unix uniq -c command. Given a list of lines, collapse each run of adjacent duplicates into a single output line that shows the run's count followed by the value.

Each output line is formatted as "%7d %s".format(count, value): a 7-character right-aligned count, a single space, then the line value. Join all output lines with \n.

Function signature:

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

Example:

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

Output (when printed):
      2 a
      1 b
      3 c

The first run is two "a"s, then a single "b", then three "c"s — three output lines.


Track var prev and var count. When a NEW value comes in (or you reach end), flush the previous run with "%7d %s".format(count, prev) and reset.

Don't forget to flush AFTER the loop too. Use == for the string comparison.
if (count > 0 && lines[i] == prev) {
    count++
} else {
    if (count > 0) {
        result.add("%7d %s".format(count, prev))
    }
    prev = lines[i]
    count = 1
}


The full solution:
class Solution {
    fun uniqCount(lines: List<String>): String {
        val result = mutableListOf<String>()
        var count = 0
        var prev: String? = null
        for (i in lines.indices) {
            if (count > 0 && lines[i] == prev) {
                count++
            } else {
                if (count > 0) {
                    result.add("%7d %s".format(count, prev))
                }
                prev = lines[i]
                count = 1
            }
        }
        if (count > 0) {
            result.add("%7d %s".format(count, prev))
        }
        return result.joinToString("\n")
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Uniq V2 in Kotlin, explained

    Problem overview

    This version builds the -c flag of uniq. The function uniqCount(lines: List<String>): String collapses each run of adjacent equal lines into one output line that shows the run's length and then the value. Each output line is "%7d %s".format(count, value): the count right-aligned in 7 characters, one space, then the text. The output lines are joined by \n.

    For lines = ["a", "a", "b", "c", "c", "c"] the output, when printed, is:

          2 a
          1 b
          3 c
    

    There are three runs, so there are three output lines. The previous version only dropped duplicates. This one also has to remember how long each run was.

    Approach: track the current run

    Two variables describe the run the loop is in: prev, the text of the run, and count, how many lines it has so far. For each line there are two cases:

    • The line equals prev and a run exists: the run continues, so count grows by 1.
    • Otherwise a different line has arrived: the old run is over, so you write its output line (if there was one), then start a new run with this line and a count of 1.

    A run is only written when the next, different line arrives, so the last run has no line after it to trigger the write. After the loop you have to write it yourself. Forgetting this is the classic bug in this kind of code: everything works except the final group is silently missing.

    Step by step

    1. Create the result list in a val named result. It gets one output line for each run.
    2. Start the count at 0. A var named count holds the length of the current run, and 0 means that no run has started.
    3. Start prev as nothing. A var named prev, typed String? and set to null, remembers the text of the current run. The ? lets it hold text or nothing yet.
    4. Loop by position with for (i in lines.indices), and close the brace right away.
    5. Continue or end the run. An if checks count > 0 && lines[i] == prev, with an else beside it. Both conditions must hold for a run to continue: one exists, and this line repeats it.
    6. Extend the run. In the if branch, count++ adds 1.
    7. Close the old run. In the else branch, a nested if checks count > 0. Before the first line no run exists, so nothing is written for it.
    8. Write its output line. Inside the nested if, result.add("%7d %s".format(count, prev)). The %7d pads the number with spaces on the left up to width 7, and %s inserts the text.
    9. Start the next run. Still in the else branch, set prev = lines[i]. The line that ended the old run begins the new one.
    10. Give it a count of 1. count = 1, because the new run has one line so far.
    11. Test for an open run after the loop. Repeat the count > 0 check outside the loop. The last run is still open.
    12. Write the last run with the same result.add call as inside the loop.
    13. Join and return with result.joinToString("\n").

    The solution in Kotlin

    class Solution {
        fun uniqCount(lines: List<String>): String {
            val result = mutableListOf<String>()
            var count = 0
            var prev: String? = null
            for (i in lines.indices) {
                if (count > 0 && lines[i] == prev) {
                    count++
                } else {
                    if (count > 0) {
                        result.add("%7d %s".format(count, prev))
                    }
                    prev = lines[i]
                    count = 1
                }
            }
            if (count > 0) {
                result.add("%7d %s".format(count, prev))
            }
            return result.joinToString("\n")
        }
    }
    

    Kotlin details to know:

    • String? is a nullable type, and prev starts as null. Comparing with == is safe for nullable values: lines[i] == prev is just false when prev is null. That is why count > 0 is checked as well, so the meaning is clear.
    • "%7d %s".format(count, prev) uses Java-style format specifiers. %7d pads with spaces to width 7, so 3 becomes six spaces and 3. If the count needs more than 7 digits, the number simply prints in full and the line gets longer. Printing "%7d|".format(12345678) gives 12345678|.
    • %s accepts a String?. If prev were still null, it would print the word null. In this code the format calls only run when count > 0, which means prev has been set.
    • count++ is a statement here. It adds 1 to a var.

    Complexity

    One pass visits each line once, so the time is O(n) string comparisons, and the result list holds one string per run, which is at most n, so the space is O(n).

    Edge cases and common mistakes

    • Forgetting the last run. Without the block after the loop, ["a", "a", "b"] would lose its b.
    • Empty input. The loop never runs, count stays 0, nothing is added, and the result is the empty string.
    • Writing a run before the first line. The count > 0 test in the else branch prevents an output line for a run that doesn't exist yet.
    • Empty lines are values. ["", "", "x"] gives a count of 2 for the empty line, followed by the empty text, so that line ends with the separating space. The next line is 1 x.
    • Non-adjacent repeats. ["a", "b", "a"] gives three runs of 1, since the two a lines aren't neighbours.
    • Forgetting to reset count to 1. A new run would continue the old number.

    Testing

    These results come from running the reference solution. The count is padded to width 7:

    lines = ["a", "b", "a"]
          1 a
          1 b
          1 a
    
    lines = ["", "", "x"]
          2 
          1 x
    

    A list of twelve "z" lines gives one output line, 12 z, and an empty list gives 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