Start learning free

LESSON 24 OF 71 · PROJECTS: COMMAND-LINE TOOLS

Sort V4 in Swift: Sorting Lines by a Key Column

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -k flag baked in. Each input line is comma-separated and is guaranteed to have at least field fields (a field may be empty, as in "a,,c"). Given a 1-indexed field number, sort the lines stably by the value at that field, compared as strings by character code, and return the original lines joined by newlines (\n). Lines whose fields are equal keep their original relative order. This matches the real command sort -t, -k N,N -s in the C locale. If the list is empty, return the empty string.

Function signature:

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

Example:

Input: field = 2, lines = ["alice,30", "bob,25", "carol,40"]

Output: "bob,25\nalice,30\ncarol,40"

When printed:
bob,25
alice,30
carol,40

Swift's sort(by:) is a stable sort. Make a mutable copy of lines, then sort it with a comparator that splits each line on "," and compares the entry at field - 1.

The full solution:
class Solution {
    func sortLines(_ lines: [String], _ field: Int) -> String {
        var sortedLines = lines
        sortedLines.sort { $0.split(separator: ",", omittingEmptySubsequences: false)[field - 1] < $1.split(separator: ",", omittingEmptySubsequences: false)[field - 1] }
        return sortedLines.joined(separator: "\n")
    }
}

STEP 1 OF 3
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Sort V4 in Swift, explained

    Problem overview

    The fourth version of the sort tool adds the -k flag. sortLines(_ lines: [String], _ field: Int) -> String receives comma-separated lines and a 1-based field number. It sorts the lines stably by the text in that field, compared as strings by character code, and returns the original lines joined with "\n". Every line has at least field fields, and a field may be empty, as in "a,,c".

    For field = 2 and ["alice,30", "bob,25", "carol,40"] the keys are "30", "25" and "40", so the result is "bob,25\nalice,30\ncarol,40". An empty list gives "".

    Approach: sort with a key-extracting closure

    The previous version compared parsed numbers inside a sort closure. This one has the same shape: keep whole lines in the array, and let the closure decide the order by looking at one field of each line. The key of a line is what you get by splitting it at the commas and taking the piece at position field - 1. The fields count from 1, but array positions count from 0.

    Because keys are compared as text, "10" sorts before "9". For ["a,9", "b,10"] with field 2 the result is "b,10\na,9". Only the key comparison matters, and ties keep input order.

    Step by step

    1. Copy lines into a var named sortedLines. Sorting the copy leaves the caller's array unchanged.
    2. Sort in place with a closure that returns whether the key of $0 is smaller than the key of $1. Each key is split(separator: ",", omittingEmptySubsequences: false)[field - 1].
    3. Return sortedLines.joined(separator: "\n"). The lines come out unchanged, only reordered.

    The solution in Swift

        func sortLines(_ lines: [String], _ field: Int) -> String {
            var sortedLines = lines
            sortedLines.sort { $0.split(separator: ",", omittingEmptySubsequences: false)[field - 1] < $1.split(separator: ",", omittingEmptySubsequences: false)[field - 1] }
            return sortedLines.joined(separator: "\n")
        }
    

    Details that matter:

    • Why omittingEmptySubsequences: false. By default split throws away empty pieces. "a,,c".split(separator: ",") has 2 pieces, while with omittingEmptySubsequences: false it has 3, and the middle one is empty. Without the argument, an empty field would shift every later field one place to the left, and field - 1 would point at the wrong piece or past the end.
    • Substrings. split returns Substring values, slices of the original line, not new strings. Substring values compare with < just as strings do, so the closure needs no conversion.
    • Empty keys sort first. An empty string is smaller than any other. With ["x,b", "y,", "z,a"] and field 2, the result is "y,\nz,a\nx,b".
    • Stability. Lines with equal keys must keep their input order. The standard library's documentation doesn't promise a stable sort, but the current implementation is stable, and the lesson relies on it. With ["b,1", "a,1", "c,0", "d,1"] and field 2, the result is "c,0\nb,1\na,1\nd,1": the three lines with key "1" stay in their original order.
    • Splitting on every comparison. The closure runs for each comparison and splits both lines each time. That is simple and fits the small inputs here.

    Complexity

    Time: O(n log n) comparisons for n lines. Each comparison splits two lines, which costs time proportional to their length, on top of comparing the keys. Space: O(n) for the copy and the output, plus the temporary pieces of the two lines being compared.

    Edge cases and common mistakes

    • Off by one. Using [field] instead of [field - 1] sorts by the wrong column and can fail on the last one, because the index is past the end.
    • Dropping empty fields. Leaving out omittingEmptySubsequences: false is the common bug for lines like "a,,c".
    • Numbers compared as text. The keys are strings, so "10" comes before "9". The key column is not parsed in this version.
    • Different from sorting whole lines. Sorting by field 1 of ["alice,30", "bob,25", "carol,40"] gives "alice,30\nbob,25\ncarol,40"; only that field decides.
    • One line and empty list. A single line stays as it is, and an empty list gives "".

    Testing

    • ["alice,30", "bob,25", "carol,40"] with field 2 gives "bob,25\nalice,30\ncarol,40".
    • The same lines with field 1 give "alice,30\nbob,25\ncarol,40".
    • ["x,b", "y,", "z,a"] with field 2 gives "y,\nz,a\nx,b".
    • ["b,1", "a,1", "c,0", "d,1"] with field 2 gives "c,0\nb,1\na,1\nd,1".
    • ["a,9", "b,10"] with field 2 gives "b,10\na,9".
    • [] with field 1 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