Problem overview
This is the first version of a small sort command. The method sortLines takes a list of lines and returns them in ascending order, joined by "\n". Duplicates are all kept, and an empty list gives the empty string.
For ["banana", "apple", "cherry"] the result is "apple\nbanana\ncherry". Printed, each word is on its own line.
The order is by character code, as in LC_ALL=C sort. That means every uppercase letter comes before every lowercase letter, so "Zebra" comes before "apple", and an empty line, being the shortest string, comes first.
Approach
Python already compares strings by the code of each character, from left to right, so the built-in sorted does exactly what the task asks. There is nothing to write by hand except gluing the result into one string.
Two details matter:
sorted(lines)returns a new list and leaveslinesuntouched. The list methodlines.sort()sorts in place and returnsNone, soreturn "\n".join(lines.sort())would raise an error."\n".join(items)puts the separator between items only, so there is no newline after the last line.
How strings compare
Python compares two strings character by character using each character's code point, the number ord returns. An uppercase "Z" has code 90 and a lowercase "a" has code 97, so "Zebra" < "apple" is True. When one string is a prefix of the other, the shorter one comes first, so "app" < "apple" is True and the empty string is smaller than every other string. Characters outside ASCII follow the same rule: sorted(["é", "z", "a"]) gives ['a', 'z', 'é'], because the code of "é" is larger than that of "z".
The same function sorts any iterable of comparable items, and always returns a list: sorted("hello") is ['e', 'h', 'l', 'l', 'o']. Keep that in mind in this lesson only to remember that the input is a list of whole lines, not characters.
Step by step
- Create
sortedLinesfromsorted(lines). - Return the sorted lines joined with a newline between each two.
The solution in Python
class Solution:
def sortLines(self, lines):
sortedLines = sorted(lines)
return "\n".join(sortedLines)
The difference between sorted and sort is easy to see with a small list:
l = ["banana", "apple"]
print(sorted(l), l)
r = l.sort()
print(r, l)
['apple', 'banana'] ['banana', 'apple']
None ['apple', 'banana']
The first line shows that sorted left l alone. The second shows that l.sort() returned None and changed l itself. Here the lesson's input list stays as the caller gave it, which is the safer behaviour.
Complexity
Sorting n lines takes O(n log n) comparisons (Python's sort is Timsort), and the new list takes O(n) extra space. The join is linear in the total length of the text.
Edge cases and common mistakes
These are the results of the solution on a few inputs:
| lines | result |
|---|---|
["banana", "apple", "cherry"] | "apple\nbanana\ncherry" |
["apple", "Zebra", "", "banana", "apple"] | "\nZebra\napple\napple\nbanana" |
["b"] | "b" |
[] | "" |
- In the second row the empty line comes first, which is why the result starts with
\n, and"Zebra"precedes both"apple"s. - Numbers written as text sort as text:
sorted(["10", "9", "1"])gives['1', '10', '9']. A later version of this tool deals with that. - Sorting without caring about case, for example with
key=str.lower, would put"apple"before"Zebra". That is not what this version asks for. - Don't add a trailing newline. The join already puts exactly one separator between each pair of lines.
