Start learning free

LESSON 21 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Sort V1 in TypeScript: Sorting Lines by Character Code

Practice Read the full explanation

Build a tiny version of the Unix sort command. Given a list of lines, return them sorted in ascending order by character code (like LC_ALL=C sort: uppercase letters come before lowercase ones, "Zebra" before "apple", and an empty line comes first), 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: "apple\nbanana\ncherry"

When printed:
apple
banana
cherry

Array.prototype.sort mutates the array in place. To avoid touching the input, copy first with [...lines], then sort and join("\n").

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

STEP 1 OF 2
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Sort V1 in TypeScript, explained

    Problem overview

    The first version of the sort project is small. The method sortLines receives an array of strings and returns them in ascending order, joined by \n. The order is by character code, like LC_ALL=C sort: uppercase letters come before lowercase ones, so "Zebra" sorts before "apple", and an empty line comes first. Duplicates are all kept, and an empty array gives the empty string.

    For ["banana", "apple", "cherry"] the result is "apple\nbanana\ncherry". Printed, each name sits on its own line.

    Approach: sort a copy, then join

    JavaScript arrays have a built-in sort() method, and its default behaviour is exactly what this lesson asks for. Without a comparator function, sort() converts the elements to strings and compares them by UTF-16 code unit. For ASCII text that is the character code, so uppercase (65 to 90) comes before lowercase (97 to 122), and the empty string is smaller than any other string.

    There is one catch: sort() reorders the array it is called on and also returns that same array. If sortLines sorted lines directly, the caller's own array would change as a side effect. The fix is to sort a copy. Spreading the array into a new one, [...lines], makes a shallow copy cheaply, and the sort then touches only the copy.

    Step by step

    1. Copy and sort. Create a const named sortedLines, typed string[], from [...lines].sort(). The spread comes first, then sort() runs on the new array. The variable is const because it is never reassigned; sorting changes the array's contents, not which array the name points to.
    2. Join with newlines. Return sortedLines.join("\n"). The separator goes only between elements, so there is no newline after the last line, and an empty array joins to "".

    The solution in TypeScript

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

    Language details

    • The type annotation string[] only helps the compiler and your editor. TypeScript erases it when it compiles to JavaScript.
    • Copying matters. After [...lines].sort() the input array keeps its original order; after calling lines.sort() directly, it would be sorted too.
    • A comparator is optional. Here the default is the right order, so none is passed. The next lessons of this project pass one when the default is wrong.

    Complexity

    Copying is O(n) and sorting is O(n log n) comparisons, so the time is O(n log n) for n lines, times the cost of comparing two strings. The copy and the joined result need O(n) extra space.

    Edge cases and common mistakes

    • Mutating the input. lines.sort() without the spread returns the right text but reorders the caller's array. For ["b", "a"] the input stays ["b", "a"] with the copy, and would become ["a", "b"] without it.
    • Case. Sorting by character code is not dictionary order. ["Zebra", "apple", ""] gives "\nZebra\napple": the empty line first, then "Zebra", then "apple".
    • Numbers written as text. The default order is text order, so ["100", "20", "3"] gives "100\n20\n3". Sorting such lines by value needs a comparator.
    • Duplicates. They stay: ["b", "a", "b"] gives "a\nb\nb".
    • Empty input. [] gives "".

    Testing

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