Problem overview
The third version of the sort tool adds -n, numeric sorting. Each line is the text of a 32-bit integer: an optional leading -, no +, and leading zeros such as "007" allowed. The method sortLines sorts the lines by their numeric value, ascending, and returns the original strings joined by \n. Lines with the same value keep their original relative order. An empty list gives "".
For ["100", "20", "3", "10"] the answer is "3\n10\n20\n100".
Plain string order gets this wrong. Text is compared one character at a time, so "100" comes before "20" because '1' is smaller than '2'. The same four lines sorted as text come out as 10, 100, 20, 3. The sort has to compare numbers while the list keeps holding strings.
Approach: sort strings with a comparator that parses them
You don't need to convert the list to integers and back. Converting would lose the original text: "007" would become 7, and the answer must still say "007". Instead the strings stay in the list, and a comparator decides which of two lines is smaller by parsing both into int values.
Comparator.comparingInt builds such a comparator from a function that maps each element to an int. The function here is Integer::parseInt, a method reference to the method that turns a string into an int. The comparator parses two lines, compares the two numbers, and the sort arranges the list accordingly.
The sort used by Collections.sort is stable, so lines with equal numeric values stay in their original order. "007" and "7" both parse to 7, and whichever came first in the input stays first in the output.
Step by step
- Copy the input into a new
ArrayListcalledsortedLines, so the caller's list isn't reordered. - Sort with a numeric comparator. Pass
Comparator.comparingInt(Integer::parseInt)as the second argument ofCollections.sort, so lines are compared by number instead of by characters. - Join with newlines using
String.join("\n", sortedLines)and return the result.
The solution in Java
class Solution {
public String sortLines(List<String> lines) {
List<String> sortedLines = new ArrayList<>(lines);
Collections.sort(sortedLines, Comparator.comparingInt(Integer::parseInt));
return String.join("\n", sortedLines);
}
}
Details worth knowing:
Integer::parseIntaccepts the lesson's formats. A leading-is fine, and so are leading zeros:"007"parses as 7. A line that isn't a validint, such as"x", makes the sort throwNumberFormatException.- The comparator returns an
intcomparison, not a difference.comparingIntcompares the two keys withInteger.compare. Writing your own comparator asInteger.parseInt(a) - Integer.parseInt(b)is a classic bug: the subtraction can overflow. For["2147483647", "-2147483648", "0"]that version returns2147483647 0 -2147483648, which is not sorted, whilecomparingIntreturns-2147483648 0 2147483647. - Method references.
Integer::parseIntis shorthand for the lambdas -> Integer.parseInt(s). - Imports.
List,ArrayList,CollectionsandComparatorare injava.util.
Complexity
Time: O(n log n) comparisons for n lines. Each comparison parses two short strings, which takes time proportional to their length (at most about 11 characters for a 32-bit integer), so the parsing adds only a constant factor. The key is recomputed at each comparison and not cached.
Space: O(n). The copy holds one reference per line, and the result string holds the text.
Edge cases and common mistakes
- Negative numbers.
["-5", "007", "7", "-12", "0", "2147483647", "-2147483648"]gives"-2147483648\n-12\n-5\n0\n007\n7\n2147483647". - Equal values written differently.
["7", "007", "07"]stays"7\n007\n07", and["007", "7", "07"]stays"007\n7\n07". The sort never compares the text of tied lines, and the output keeps the original strings. - Sorting text.
Collections.sort(sortedLines)with no comparator gives the text order of version 1, which is wrong here. - Parsing into a new list. If you convert to integers and back, leading zeros disappear and
"007"comes back as"7". - Empty list.
[]gives"", and the comparator is never called.
Testing
["100", "20", "3", "10"]gives"3\n10\n20\n100".["-5", "007", "7", "-12", "0", "2147483647", "-2147483648"]gives"-2147483648\n-12\n-5\n0\n007\n7\n2147483647".["7", "007", "07"]gives"7\n007\n07".[]gives"".
