Start learning free

LESSON 22 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Sort V2 in TypeScript: Reverse Sort with sort() and reverse()

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -r flag baked in. Given a list of lines, return them sorted in descending order by character code (the exact reverse of v1's order, like LC_ALL=C sort -r: lowercase letters come before uppercase ones), joined by newline characters (\n). Duplicates are all kept. If the list is empty, return the empty string.

Function signature:

sortLines(lines: string[]): string

Example:

Input: lines = ["banana", "apple", "cherry"]

Output: "cherry\nbanana\napple"

When printed:
cherry
banana
apple

Sort ascending first, then call .reverse(). Copy the array first (e.g. with the spread operator) to avoid mutating the input.

The full solution:
class Solution {
    sortLines(lines: string[]): string {
        const sortedLines: string[] = [...lines].sort().reverse();
        return sortedLines.join("\n");
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Sort V2 in TypeScript, explained

    Problem overview

    The second version of the sort project adds the effect of the -r flag. sortLines still takes an array of strings and returns one string joined by \n, but now the order is descending by character code, the exact reverse of the previous version: lowercase letters come before uppercase ones. Duplicates are kept, and an empty array gives "".

    For ["banana", "apple", "cherry"] the result is "cherry\nbanana\napple".

    Approach: ascending order, turned around

    The previous version already knows how to sort by character code with the default sort(). Descending order is that same order read backwards, so one extra call is enough: reverse(), which flips an array in place and returns it. Sort first, reverse second.

    The same warning as before applies to both methods. sort() and reverse() both modify the array they are called on, so the code must work on a copy, made with the spread [...lines]. Chaining makes it short: the copy is sorted, and the sorted copy is reversed, so the caller's array is never touched.

    An alternative is a comparator that compares the other way round. It works too, but the sort-then-reverse version states the idea plainly, and for strings that are equal the two orders cannot be told apart, so ties raise no question.

    One more reason the order matters: reversing the ascending result is only correct because the ascending order is a total order on the lines. Two equal lines are identical strings, so it makes no difference which one ends up first.

    Step by step

    1. Copy, sort and reverse. Create const sortedLines: string[] from [...lines].sort().reverse(). The spread makes the copy, sort() puts it in ascending order and reverse() flips it, so the largest string comes first.
    2. Join with newlines. Return sortedLines.join("\n"). As before, join places the separator only between lines, so there is no trailing newline.

    The solution in TypeScript

    class Solution {
        sortLines(lines: string[]): string {
            const sortedLines: string[] = [...lines].sort().reverse();
            return sortedLines.join("\n");
        }
    }
    

    Language details

    • Method chaining works because sort() returns the array it sorted, so .reverse() can be called on the result. Both calls act on the copy created by the spread.
    • Without a comparator, sort() compares strings by UTF-16 code unit, which for ASCII text is the character code. That is why "b" ends up before "B" in the reversed result.
    • Reversing is not the same as sorting with localeCompare or sorting case-insensitively. This lesson wants the raw code order.

    Complexity

    The copy and the reverse() are O(n) and the sort is O(n log n), so the total time is O(n log n) comparisons. The copy and the final string use O(n) extra space.

    Edge cases and common mistakes

    • Forgetting reverse(). The result would be ascending, identical to the previous version.
    • Mixed case. ["b", "B", "a", ""] gives "b\na\nB\n". Lowercase letters come first, then uppercase ones, and the empty line comes last, because in descending order the smallest string is last. The text ends with a newline because its last line is empty.
    • Duplicates. They stay: ["a", "c", "a"] gives "c\na\na".
    • Mutating the input. Skip the spread and the caller's array is sorted and reversed in place.
    • Empty input. [] gives "".

    Testing

    InputResult
    ["banana", "apple", "cherry"]"cherry\nbanana\napple"
    ["b", "B", "a", ""]"b\na\nB\n"
    ["a", "c", "a"]"c\na\na"
    []""
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free