Problem overview
Version 4 of the sort project adds -k, sorting by one field. The lines of sortLines(lines: Array[String], field: Int): String are comma-separated, and every line has at least field fields. The fields count from 1, and a field may be empty, as in "a,,c". The method sorts the lines stably by that field, compared as strings by character code, and returns the original lines joined by \n.
For field = 2 and ["alice,30", "bob,25", "carol,40"], the second fields are "30", "25" and "40". Sorted as text they run "25", "30", "40", so the answer is "bob,25\nalice,30\ncarol,40". Lines whose fields are equal keep their original order, and an empty array gives the empty string.
Approach
This is a sort by key again, as in the numeric version, except that now the key is a piece of the line. For each line you split at the commas, take the piece at the requested position, and use it as the sort key. sortBy returns the whole original lines, ordered by those keys, and since it is stable, equal keys keep their input order without any extra work.
The key is a String, so the comparison is by character code. That means "10" sorts before "9": with field = 2, the lines ["p,9", "q,10"] become "q,10\np,9".
Step by step
- Create
val sortedLinesfromlines.sortBywith a functionl => ...that gives the key of linel. - For the key, call
l.split(",", -1)and index the result withfield - 1. Fields count from 1 but array positions from 0, so field 2 is at position 1. Scala indexes with parentheses, not square brackets. - Return
sortedLines.mkString("\n"), with a newline between lines and none after the last.
The solution in Scala
class Solution {
def sortLines(lines: Array[String], field: Int): String = {
val sortedLines = lines.sortBy(l => l.split(",", -1)(field - 1))
return sortedLines.mkString("\n")
}
}
Why split takes -1
The second argument of split is a limit. With the one-argument form, split drops empty pieces at the end: "a,b,".split(",") gives a, b, only two pieces. Asking for field 3 of that line would then fail with an ArrayIndexOutOfBoundsException (Index 2 out of bounds for length 2), even though the line really has a third, empty field.
A negative limit, here -1, keeps those trailing empty pieces: "a,b,".split(",", -1) gives a, b and an empty string. The lesson says a field may be empty, so this detail is needed for lines such as "a,b,".
Other details
- Empty fields are ordinary strings. The empty string is smaller than any other, so lines with an empty key come first.
- Uppercase comes before lowercase here too. With
field = 2, the lines["a,b,c", "a,,c", "a,B,c"]are ordered"a,,c\na,B,c\na,b,c". - The comma is passed to
splitas text, and it is also a pattern. A comma has no special meaning in a pattern, so no escaping is needed. Other separators, such as"|"or".", would need care.
Complexity
Each line is split once per comparison it takes part in, because the key function can be called again for the same element during the sort. With n lines of length at most m, that means O(n log n) comparisons, each costing up to O(m) to split and compare. The sorted copy and the joined result add O(n) space for the array, plus the text itself.
Edge cases and common mistakes
- Stability. With
field = 2,["x,2", "y,1", "z,2", "w,1"]gives"y,1\nw,1\nx,2\nz,2": within each key, the lines stay in their input order. - Off by one. Using
(field)instead of(field - 1)reads the wrong piece and can run past the end of the line. - Trailing empty field. With
field = 3,["a,b,", "c,a,z", "d,c,"]gives"a,b,\nd,c,\nc,a,z", because two lines have an empty third field. Without the-1that input would throw. - Numbers as text. The field is compared as text, so
"10"comes before"9". - Empty array. The result is
"".
