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
- Copy.
lines.toMutableList()makes a list you can reorder, and leaves the input list as it was. - 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 positionfield - 1. The line itself is what ends up in the list; the piece is only the sort key. - 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. sortByis 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 throwsIndexOutOfBoundsExceptionif 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:
| Lines | field | Result |
|---|---|---|
["alice,30", "bob,25", "carol,40"] | 2 | bob,25|alice,30|carol,40 |
["alice,30", "bob,25", "carol,40"] | 1 | alice,30|bob,25|carol,40 |
["x,b", "y,a", "z,b", "w,a"] | 2 | y,a|w,a|x,b|z,b |
["p,b,1", "q,,2", "r,a,3"] | 2 | q,,2|r,a,3|p,b,1 |
["a,30", "b,4", "c,100"] | 2 | c,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
sortByand the lines themselves stay in the list. - Losing stability. Ties must keep their input order.
sortBydoes 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.
