Start learning free

LESSON 623 OF 675 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: sort v1 — Ascending Alphabetical Sort

Practice

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