Start learning free

LESSON 24 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Sort -k in Kotlin: Stable Sort by Column

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -k flag baked in. Each input line is comma-separated and is guaranteed to have at least field fields (a field may be empty, as in "a,,c"). Given a 1-indexed field number, sort the lines stably by the value at that field, compared as strings by character code, and return the original lines joined by newlines (\n). Lines whose fields are equal keep their original relative order. This matches the real command sort -t, -k N,N -s in the C locale. If the list is empty, return the empty string.

Function signature:

fun sortLines(lines: List<String>, field: Int): String

Example:

Input: field = 2, lines = ["alice,30", "bob,25", "carol,40"]

Output: "bob,25\nalice,30\ncarol,40"

When printed:
bob,25
alice,30
carol,40

Copy the list with toMutableList(), then call sortBy with a selector that splits each line on "," and returns the field - 1 element. Kotlin's sortBy is a stable sort.

The full solution:
class Solution {
    fun sortLines(lines: List<String>, field: Int): String {
        val sortedLines = lines.toMutableList()
        sortedLines.sortBy { it.split(",")[field - 1] }
        return sortedLines.joinToString("\n")
    }
}

STEP 1 OF 3
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Sort V4 in Kotlin, explained

    Problem overview

    Version 4 of the sort project adds the -k flag. Each line holds comma-separated fields, and every line has at least field of them. A field may be empty, as in "a,,c". sortLines(lines: List<String>, field: Int): String sorts the lines by the value of one field. The field number is 1-indexed. The values are compared as strings by character code, and the lines are returned whole, joined with \n.

    The sort is stable: lines whose chosen field is equal keep their original relative order. For field = 2 and ["alice,30", "bob,25", "carol,40"] the keys are "30", "25" and "40", so the result is "bob,25\nalice,30\ncarol,40".

    Approach

    This version combines two earlier ideas. Like the numeric version, it sorts whole lines by a key computed from each line. Unlike it, the key is a piece of text, so the comparison is the ordinary string order of the first version.

    Computing the key takes two operations: split the line at its commas, then pick the piece at the right position. Fields are counted from 1, but list positions are counted from 0, so the piece for field N sits at position field - 1.

    Step by step

    1. Copy. lines.toMutableList() makes a list you can reorder, and leaves the input list as it was.
    2. Sort by the field. sortedLines.sortBy { it.split(",")[field - 1] } sorts the copy in place. For each line, it, the lambda splits at commas and takes the piece at position field - 1. The line itself is what ends up in the list; the piece is only the sort key.
    3. Join with newlines. joinToString("\n") glues the lines together with a separator between them.

    The solution in Kotlin

    class Solution {
        fun sortLines(lines: List<String>, field: Int): String {
            val sortedLines = lines.toMutableList()
            sortedLines.sortBy { it.split(",")[field - 1] }
            return sortedLines.joinToString("\n")
        }
    }
    

    Kotlin details in this code

    • split(",") keeps empty fields. "a,,c".split(",") is the list [a, , c] with three elements, so field 2 is the empty string. A trailing comma also gives a trailing empty piece: "a,".split(",") has two elements. Empty keys are ordinary strings, and the empty string sorts before every other string.
    • The key is a String, so lines are compared by character code, as the lesson requires. A key such as "100" sorts before "30" because '1' is less than '3'. If a field holds numbers, they are not compared as numbers in this version.
    • sortBy is stable, which gives the tie rule for free. Lines whose keys are equal stay in the order they had in the input.
    • The key is a lookup by index. [field - 1] on a list throws IndexOutOfBoundsException if the line has fewer fields. The lesson guarantees enough fields, so no check is needed.
    • The lambda runs on lines, not on pieces, so the sorted list contains the original lines unchanged, commas included.

    Complexity

    With n lines, sorting takes O(n log n) comparisons. The key function splits a line, which costs time proportional to the line's length. The extra space is the copied list and the result string, plus the short-lived lists that split creates.

    Testing

    These inputs and the results the solution returns, with \n shown as a bar:

    LinesfieldResult
    ["alice,30", "bob,25", "carol,40"]2bob,25|alice,30|carol,40
    ["alice,30", "bob,25", "carol,40"]1alice,30|bob,25|carol,40
    ["x,b", "y,a", "z,b", "w,a"]2y,a|w,a|x,b|z,b
    ["p,b,1", "q,,2", "r,a,3"]2q,,2|r,a,3|p,b,1
    ["a,30", "b,4", "c,100"]2c,100|a,30|b,4

    In the third row, y,a stays ahead of w,a and x,b stays ahead of z,b, because equal keys keep their input order. In the fourth row the empty field of q,,2 puts it first. In the last row the keys "100", "30" and "4" are compared as text.

    Edge cases and common mistakes

    • Off-by-one on the field number. it.split(",")[field] would pick the wrong piece, or fail on the last field. Field 1 is position 0.
    • Sorting the pieces instead of the lines. The output must contain the original lines, so the key goes inside sortBy and the lines themselves stay in the list.
    • Losing stability. Ties must keep their input order. sortBy does that; a hand-written sort might not.
    • Empty fields. They are valid keys and come first.
    • Empty list. The result is "", and the key function never runs.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free