Start learning free

LESSON 23 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Sort V3 in TypeScript: Numeric Sort with a Comparator

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -n flag baked in. Each input line is the string form of an integer that fits in 32 bits (an optional leading -, no leading +; leading zeros such as "007" are allowed). Sort the lines numerically (not lexicographically) in ascending order, and return the original strings joined by newlines (\n). Lines with the same numeric value keep their original relative order (a stable sort). The real sort -n would break such ties by comparing the text; this version does not. If the list is empty, return the empty string.

Note: lexicographic sort would put "100" before "20"; numeric sort puts 20 before 100.

Function signature:

sortLines(lines: string[]): string

Example:

Input: lines = ["100", "20", "3", "10"]

Output: "3\n10\n20\n100"

When printed:
3
10
20
100

Pass a numeric comparator to sort: (a, b) => +a - +b. The unary + coerces a string to a number.

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

STEP 1 OF 2
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Sort V3 in TypeScript, explained

    Problem overview

    The third version of the sort project adds the effect of the -n flag. Every line in the input is the text form of a 32-bit integer: an optional leading -, no +, and leading zeros such as "007" are allowed. sortLines must sort the lines by numeric value, ascending, and return the original strings joined by \n.

    Lines with the same value keep their original relative order, so the sort must be stable. An empty array gives "".

    For ["100", "20", "3", "10"] the result is "3\n10\n20\n100". The default sort() would give "10\n100\n20\n3", because it compares text: "10" is a prefix of "100", and "100" starts with "1", which is smaller than "2" and "3".

    Approach: give sort() a comparator

    The default order is the wrong one here, so sort() needs a comparator: a function of two elements, a and b, that returns a negative number if a belongs first, a positive number if b belongs first and zero if they are tied. For numbers, a - b does exactly this.

    The elements are strings, so they must become numbers before subtracting. A unary plus does that: +"007" is 7 and +"-12" is -12. Leading zeros disappear in the conversion, which is what we want for comparing, while the array still holds the original strings, so the output keeps "007" as it was.

    Ties are handled by the language. Since ES2019, Array.prototype.sort is required to be stable, and Node 22 follows it. Two lines with the same value, such as "7" and "007", stay in their input order, as the lesson requires. The real sort -n would break such ties by comparing the text; this version does not.

    Step by step

    1. Copy and sort with a comparator. Create const sortedLines: string[] from [...lines].sort(...). The spread copies the array so the caller's array is not reordered. The comparator is the arrow function (a, b) => +a - +b: convert both strings to numbers and subtract.
    2. Join with newlines. Return sortedLines.join("\n"), with no trailing newline.

    The solution in TypeScript

    class Solution {
        sortLines(lines: string[]): string {
            const sortedLines: string[] = [...lines].sort((a, b) => +a - +b);
            return sortedLines.join("\n");
        }
    }
    

    Language details

    • +a - +b reads as (+a) - (+b). The unary + turns a string into a number; without it, a - b on two strings would be reported as a type error by the compiler, although the JavaScript it produces would still convert the strings when subtracting.
    • In TypeScript, number is a 64-bit floating-point value. Every 32-bit integer is represented exactly, and the difference of two of them is at most about 4.3 billion, far below the point where doubles lose integer precision, so the subtraction never overflows or rounds. In a language with 32-bit int the same trick could overflow, but not here.
    • The comparator must return a consistent number for each pair. Returning a boolean such as a > b is a classic bug: true and false become 1 and 0, so "a goes first" can never be expressed.

    Complexity

    The sort makes O(n log n) comparisons, each converting two short strings, so the time is O(n log n) for n lines. The copy and the result use O(n) extra space.

    Edge cases and common mistakes

    • Using the default sort(). ["100", "20", "3", "10"] would sort as text and give "10\n100\n20\n3".
    • Negative numbers. ["-5", "3", "-12"] gives "-12\n-5\n3". The comparison is numeric, so the minus sign counts as a sign, not as a character.
    • Leading zeros and ties. ["7", "007", "6"] gives "6\n7\n007", and ["007", "7", "7"] gives "007\n7\n7". Equal values keep their input order.
    • Extreme values. ["2147483647", "-2147483648", "0"] gives "-2147483648\n0\n2147483647".
    • Returning the numbers instead of the strings. Mapping the lines to numbers first would lose "007". Sort the original strings and convert only inside the comparator.
    • Empty input. [] gives "".

    Testing

    InputResult
    ["100", "20", "3", "10"]"3\n10\n20\n100"
    ["-5", "3", "-12"]"-12\n-5\n3"
    ["7", "007", "6"]"6\n7\n007"
    ["007", "7", "7"]"007\n7\n7"
    []""
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free