Start learning free

LESSON 23 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Sort -n in Kotlin: Numeric Order with sortBy

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -n flag baked in. Each input line is the string form of an integer that fits in 32 bits (an optional leading -, no leading +; leading zeros such as "007" are allowed). Sort the lines numerically (not lexicographically) in ascending order, and return the original strings joined by newlines (\n). Lines with the same numeric value keep their original relative order (a stable sort). The real sort -n would break such ties by comparing the text; this version does not. If the list is empty, return the empty string.

Note: lexicographic sort would put "100" before "20"; numeric sort puts 20 before 100.

Function signature:

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

Example:

Input: lines = ["100", "20", "3", "10"]

Output: "3\n10\n20\n100"

When printed:
3
10
20
100

Copy to a mutable list and call sortBy { it.toInt() } so the order is numeric, then build the result with joinToString.

The full solution:
class Solution {
    fun sortLines(lines: List<String>): String {
        val sortedLines = lines.toMutableList()
        sortedLines.sortBy { it.toInt() }
        return sortedLines.joinToString("\n")
    }
}

STEP 1 OF 3
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Sort V3 in Kotlin, explained

    Problem overview

    Version 3 of the sort project adds the -n flag. Each line of the input is the text of a 32-bit integer: an optional leading -, no +, and leading zeros such as "007" are allowed. sortLines(lines: List<String>): String must sort the lines by their numeric value, ascending, and return the original strings joined with \n.

    Sorting numbers as text puts "100" before "20", because '1' is smaller than '2'. Numeric sorting puts 20 first. For ["100", "20", "3", "10"] the result is "3\n10\n20\n100".

    Lines with the same numeric value keep their original relative order. That's a stable sort, and it differs from the real sort -n, which breaks ties by comparing the text.

    Approach

    The lines have to stay strings, because the output shows them exactly as given, including leading zeros. What changes is the key used to compare them. Instead of comparing the strings, compare the integers they spell. Kotlin's sortBy does just that: you give it a function that computes a key from each element, and it orders the elements by their keys.

    Plain sort() on these strings would compare them by character code, which is the previous versions' behaviour and the wrong order here. Here is the difference for the lesson's example:

    Sorted byResult (\n shown as a bar)
    Character code, sort()10|100|20|3
    Numeric value, sortBy { it.toInt() }3|10|20|100

    Step by step

    1. Copy into a mutable list. lines.toMutableList() gives a list you may reorder, and leaves the caller's list alone.
    2. Sort by number. sortedLines.sortBy { it.toInt() } sorts the copy in place. For each line, called it inside the lambda, toInt() reads the number the text spells, and the list is ordered by those numbers.
    3. Join with newlines. joinToString("\n") puts the separator between lines only.

    The solution in Kotlin

    class Solution {
        fun sortLines(lines: List<String>): String {
            val sortedLines = lines.toMutableList()
            sortedLines.sortBy { it.toInt() }
            return sortedLines.joinToString("\n")
        }
    }
    

    Kotlin details in this code

    • The list still holds strings. toInt() is only used to compute the sort key. The elements of sortedLines are never replaced, so "007" stays "007" in the output.
    • String.toInt() understands leading zeros and a minus sign. "007".toInt() is 7 and "-12".toInt() is -12. It returns an Int, which is 32 bits, so every value the lesson allows fits, from -2147483648 to 2147483647. A string that isn't a valid Int, such as "2147483648", throws a NumberFormatException. The lesson guarantees valid input, so you don't need toIntOrNull() here.
    • sortBy is stable. Elements whose keys are equal stay in their original order. That is exactly the tie rule of this lesson: ["007", "7", "07"] comes back in the same order, since all three have the value 7.
    • Comparing keys, not subtracting them. sortBy compares the Int keys safely. A hand-written comparator that returns a - b could overflow for numbers near the ends of the Int range, and the lesson's range includes both ends.

    Complexity

    Sorting n lines takes O(n log n) comparisons. The key function is cheap, proportional to the length of the line. The extra space is the copied list plus the result string.

    Edge cases and common mistakes

    • Sorting as text. Calling sort() gives 10|100|20|3 for the example. Whenever numbers have different digit counts, the text order differs from the numeric order.
    • Negative numbers and the extremes. For ["007", "7", "-5", "10", "0", "-12", "2147483647", "-2147483648"] the result is -2147483648, -12, -5, 0, 007, 7, 10, 2147483647. The keys are real integers, so negatives sort correctly, the smallest value comes first and the largest last.
    • Leading zeros and ties. ["007", "7", "07"] comes back in the same order, and so does ["7", "007", "07"]: all three lines have the value 7, so the input order decides. Don't output toInt() results, or "007" would turn into "7".
    • Empty list. The result is "". 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