Problem overview
Version 3 of the sort project adds -n, numeric sorting. Each line of sortLines(lines: Array[String]): String is the text of a 32-bit integer: an optional leading -, no +, and leading zeros such as "007" allowed. The method sorts the lines by numeric value, ascending, and returns the original strings joined by \n. An empty array gives the empty string.
For ["100", "20", "3", "10"] the answer is "3\n10\n20\n100". Sorted as text, the same lines would give "10\n100\n20\n3", because "100" is compared character by character and '1' is smaller than '2'.
When two lines have the same value, such as "7" and "007", they keep their original relative order. The real sort -n would settle such ties by comparing the text, but this version doesn't.
Approach: sort by a key, return the original
You want to order the strings by a number that is computed from each string, while keeping the strings themselves in the output. That is exactly what sortBy does: it takes a function that maps each element to a key, orders the elements by their keys, and returns the elements, not the keys. So the key function is _.toInt, which parses a line into an Int.
Because "007" stays "007" in the output, the text of every line survives, leading zeros included. Only the comparison uses the parsed numbers.
Step by step
- Create
val sortedLinesfromlines.sortBy(_.toInt). The shorthand_.toIntmeansline => line.toInt. - Return
sortedLines.mkString("\n"), which places a newline between each two lines and none after the last.
The solution in Scala
class Solution {
def sortLines(lines: Array[String]): String = {
val sortedLines = lines.sortBy(_.toInt)
return sortedLines.mkString("\n")
}
}
Scala details to be aware of:
toInton a string parses it as a decimal number."007".toIntis 7 and"-0".toIntis 0, so leading zeros and a negative sign are handled for you.- A line that is not a number makes
toIntthrow aNumberFormatException. For the input["1", "abc"]the message isFor input string: "abc". The lesson guarantees valid integers, so you don't need to guard against it here. Intis 32 bits, which is why the statement limits the values to that range. The extremes-2147483648and2147483647parse and sort correctly:["2147483647", "-2147483648", "0"]gives"-2147483648\n0\n2147483647".sortByis a stable sort: elements with equal keys stay in their original order. That is how the tie rule from the statement is met without any extra code.- The result of
sortByon anArray[String]is a new array, solinesis not modified.
Complexity
Sorting n lines takes O(n log n) comparisons of integers. The key function may run again for the same element during the sort, but each parse is short, so the overall bound stays the same. The sorted copy and the joined result take O(n) space.
Edge cases and common mistakes
- Sorting as text. Calling
lines.sortedinstead puts"100"before"20". The key function is what makes the order numeric. - Negative numbers.
["-5", "3", "-20", "0"]gives"-20\n-5\n0\n3". As text,"-5"would sort before"-20", which is wrong numerically. - Equal values.
["7", "007", "7", "07"]comes out unchanged,"7\n007\n7\n07", since all four lines equal 7. With["007", "7"]the result is"007\n7": the original order wins, not the text. - Converting the lines first. Parsing every line to an
Intand sorting those numbers would lose the original text, so"007"would print as7. Sort the strings by a key instead. - Empty array. The result is
"".
