Problem overview
This is the first version of a small sort command. The method sortLines(lines) receives an array of strings and returns them in ascending order, joined by \n into one string. Duplicates are kept, and an empty array gives an empty string.
The order is by character code, not by dictionary rules. Every character has a numeric code, and strings are compared character by character using those numbers. All uppercase letters have smaller codes than all lowercase letters, so "Zebra" comes before "apple". An empty string is smaller than any other string, so an empty line comes first.
For ["banana", "apple", "cherry"] the result is "apple\nbanana\ncherry".
Approach: sort a copy, then join
JavaScript already has what is needed. When Array.prototype.sort() gets no comparator, it converts the elements to strings and compares them by their UTF-16 code units, which for ordinary text means by character code. That is exactly the order the task asks for.
There is one catch. sort() reorders the array it is called on and returns that same array. A function that sorts its parameter directly would reorder the caller's array as a side effect. The lesson avoids this by copying first.
Step by step
- Copy and sort. Spread the input into a new array with
[...lines], callsort()on the copy and store the result in the constantsortedLines. The copy is the array that gets reordered, solinesstays as it was. - Join and return.
join("\n")glues the elements together with a newline between each pair. The separator goes only between elements, so there is no newline after the last line, and an empty array produces"".
The solution in JavaScript
class Solution {
sortLines(lines) {
const sortedLines = [...lines].sort();
return sortedLines.join("\n");
}
}
Some details of this code:
- Why the copy is needed. Arrays are passed by reference, so both the caller and the method see the same array. With
const orig = ["b", "a"], callingorig.sort()turnsoriginto["a", "b"]. With the spread copy,origremains["b", "a"]. - The default order is textual. For numbers it gives surprising results:
[10, 9, 1].sort()is[1, 10, 9], because"10"is compared with"9"as text. That is harmless here, since every element is a string, but it matters in the next kinds of sort. constdoes not freeze the array. It only stopssortedLinesfrom being reassigned. The array behind it can still change, which is why the copy matters.
Complexity
Time: O(n log n) comparisons for n lines, from the sort. Each comparison looks at the strings' characters, so the real cost also grows with line length. Copying and joining are linear in the total size of the text.
Space: O(n) for the copy of the array, plus the output string.
Edge cases and common mistakes
- Empty array.
[]returns"". - Empty line.
["apple", "Zebra", "", "banana", "apple"]gives"\nZebra\napple\napple\nbanana": the empty line first, then"Zebra", then the lowercase words, with both"apple"s kept. - Sorting the input directly.
lines.sort().join("\n")returns the right text but reorders the caller's array. - Expecting dictionary order. The default sort does not ignore case. If you wanted
"apple"before"Zebra", you would need a comparator such aslocaleCompare, which is a different order from the one asked for here. - Joining with a trailing newline. Adding
"\n"after the last line would make the output differ from the expected text.
Testing
["banana", "apple", "cherry"]gives"apple\nbanana\ncherry".["apple", "Zebra", "", "banana", "apple"]gives"\nZebra\napple\napple\nbanana".[]gives"".
