Start learning free

LESSON 21 OF 71 · PROJECTS: COMMAND-LINE TOOLS

Sort V1 in Swift: Alphabetical Order with sort()

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:

func sortLines(_ lines: [String]) -> String

Example:

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

Output: "apple\nbanana\ncherry"

When printed:
apple
banana
cherry

Copy the input into a fresh var array, sort it in place with sort(), then stitch it back together with joined(separator:).

The full solution:
class Solution {
    func sortLines(_ lines: [String]) -> String {
        var sortedLines = lines
        sortedLines.sort()
        return sortedLines.joined(separator: "\n")
    }
}

STEP 1 OF 3
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Sort V1 in Swift, explained

    Problem overview

    The first version of the sort tool is one function: sortLines(_ lines: [String]) -> String. It sorts the lines in ascending order and returns them joined by "\n". Duplicates are kept, and an empty list gives the empty string.

    The order is by character code, not by dictionary rules. Every uppercase letter sorts before every lowercase letter, so "Zebra" comes before "apple", and an empty line comes first of all. For ["banana", "apple", "cherry"] the result is "apple\nbanana\ncherry".

    Approach: sort a copy, then join

    Swift already knows how to order strings: the < operator on two String values compares them character by character, and for plain ASCII text that is the same as comparing character codes. So the whole job is to sort the array with its default order and then glue the lines together.

    There are two ways to sort in Swift. sort() rearranges an array in place and needs a var. sorted() leaves the array alone and returns a new one. This lesson uses the in-place version on a copy, which keeps the caller's array untouched.

    Step by step

    1. Copy the parameter into a var named sortedLines. Function parameters are constants, so you can't sort lines itself. Arrays are value types in Swift: var sortedLines = lines makes an independent copy, and sorting it does not change the caller's array.
    2. Call sort() on the copy. With no arguments it uses the ascending order of the elements, and it returns nothing.
    3. Return sortedLines.joined(separator: "\n"). The separator goes between lines, so there is no newline after the last one.

    The solution in Swift

        func sortLines(_ lines: [String]) -> String {
            var sortedLines = lines
            sortedLines.sort()
            return sortedLines.joined(separator: "\n")
        }
    

    Details that matter:

    • sort() versus sorted(). sort() mutates the array and returns nothing, so there is no sorted array to return from it. Use sorted() when you want a new array back, and sort() when you want to change a var in place.
    • Copy on assignment. Because arrays are values, the copy is cheap to write. After sortLines(["b", "a"]), the array that was passed in is still ["b", "a"].
    • Text order, not numeric order. ["10", "9", "1"] sorts to "1\n10\n9", because "10" starts with "1" and "9" starts with a larger character. Numeric ordering is a different problem.
    • Empty input. Sorting an empty array does nothing, and joining an empty array returns "", so no special case is needed.

    Complexity

    Time: O(n log n) comparisons for n lines, which is the cost of a comparison sort. Each comparison of two lines costs up to the length of the shorter one. Space: O(n) for the copy and for the joined string.

    Edge cases and common mistakes

    • Capital letters. ["apple", "Zebra"] returns "Zebra\napple". A learner expecting dictionary order gets surprised here.
    • The empty line. ["b", "", "a"] returns "\na\nb": the output starts with a newline because the first line is empty.
    • Duplicates stay. ["b", "a", "b"] returns "a\nb\nb". Nothing is removed.
    • Trailing newline. Appending "\n" after the last line would break the expected output. joined(separator:) avoids that.
    • Using let for the copy. A constant array can't be sorted in place, and the compiler reports an error when you call sort() on it.

    Testing

    • ["banana", "apple", "cherry"] gives "apple\nbanana\ncherry".
    • ["apple", "Zebra"] gives "Zebra\napple".
    • ["b", "", "a"] gives "\na\nb".
    • ["b", "a", "b"] gives "a\nb\nb".
    • ["10", "9", "1"] gives "1\n10\n9".
    • [] gives "".
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free