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 by | Result (\n shown as a bar) |
|---|---|
Character code, sort() | 10|100|20|3 |
Numeric value, sortBy { it.toInt() } | 3|10|20|100 |
Step by step
- Copy into a mutable list.
lines.toMutableList()gives a list you may reorder, and leaves the caller's list alone. - Sort by number.
sortedLines.sortBy { it.toInt() }sorts the copy in place. For each line, calleditinside the lambda,toInt()reads the number the text spells, and the list is ordered by those numbers. - 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 ofsortedLinesare 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 anInt, which is 32 bits, so every value the lesson allows fits, from -2147483648 to 2147483647. A string that isn't a validInt, such as"2147483648", throws aNumberFormatException. The lesson guarantees valid input, so you don't needtoIntOrNull()here.sortByis 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.
sortBycompares theIntkeys safely. A hand-written comparator that returnsa - bcould overflow for numbers near the ends of theIntrange, 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()gives10|100|20|3for 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 outputtoInt()results, or"007"would turn into"7". - Empty list. The result is
"". The key function never runs.
