Start learning free

LESSON 24 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Sort V4 in Scala: Sorting Lines by a Field with sortBy and split

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:

def sortLines(lines: Array[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

Use sortBy with a function that splits each line on "," (with limit -1, so empty trailing fields are kept) and returns the field - 1 element. Scala's sortBy is a stable sort.

The full solution:
class Solution {
    def sortLines(lines: Array[String], field: Int): String = {
        val sortedLines = lines.sortBy(l => l.split(",", -1)(field - 1))
        return sortedLines.mkString("\n")
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Sort V4 in Scala, explained

    Problem overview

    Version 4 of the sort project adds -k, sorting by one field. The lines of sortLines(lines: Array[String], field: Int): String are comma-separated, and every line has at least field fields. The fields count from 1, and a field may be empty, as in "a,,c". The method sorts the lines stably by that field, compared as strings by character code, and returns the original lines joined by \n.

    For field = 2 and ["alice,30", "bob,25", "carol,40"], the second fields are "30", "25" and "40". Sorted as text they run "25", "30", "40", so the answer is "bob,25\nalice,30\ncarol,40". Lines whose fields are equal keep their original order, and an empty array gives the empty string.

    Approach

    This is a sort by key again, as in the numeric version, except that now the key is a piece of the line. For each line you split at the commas, take the piece at the requested position, and use it as the sort key. sortBy returns the whole original lines, ordered by those keys, and since it is stable, equal keys keep their input order without any extra work.

    The key is a String, so the comparison is by character code. That means "10" sorts before "9": with field = 2, the lines ["p,9", "q,10"] become "q,10\np,9".

    Step by step

    1. Create val sortedLines from lines.sortBy with a function l => ... that gives the key of line l.
    2. For the key, call l.split(",", -1) and index the result with field - 1. Fields count from 1 but array positions from 0, so field 2 is at position 1. Scala indexes with parentheses, not square brackets.
    3. Return sortedLines.mkString("\n"), with a newline between lines and none after the last.

    The solution in Scala

    class Solution {
        def sortLines(lines: Array[String], field: Int): String = {
            val sortedLines = lines.sortBy(l => l.split(",", -1)(field - 1))
            return sortedLines.mkString("\n")
        }
    }
    

    Why split takes -1

    The second argument of split is a limit. With the one-argument form, split drops empty pieces at the end: "a,b,".split(",") gives a, b, only two pieces. Asking for field 3 of that line would then fail with an ArrayIndexOutOfBoundsException (Index 2 out of bounds for length 2), even though the line really has a third, empty field.

    A negative limit, here -1, keeps those trailing empty pieces: "a,b,".split(",", -1) gives a, b and an empty string. The lesson says a field may be empty, so this detail is needed for lines such as "a,b,".

    Other details

    • Empty fields are ordinary strings. The empty string is smaller than any other, so lines with an empty key come first.
    • Uppercase comes before lowercase here too. With field = 2, the lines ["a,b,c", "a,,c", "a,B,c"] are ordered "a,,c\na,B,c\na,b,c".
    • The comma is passed to split as text, and it is also a pattern. A comma has no special meaning in a pattern, so no escaping is needed. Other separators, such as "|" or ".", would need care.

    Complexity

    Each line is split once per comparison it takes part in, because the key function can be called again for the same element during the sort. With n lines of length at most m, that means O(n log n) comparisons, each costing up to O(m) to split and compare. The sorted copy and the joined result add O(n) space for the array, plus the text itself.

    Edge cases and common mistakes

    • Stability. With field = 2, ["x,2", "y,1", "z,2", "w,1"] gives "y,1\nw,1\nx,2\nz,2": within each key, the lines stay in their input order.
    • Off by one. Using (field) instead of (field - 1) reads the wrong piece and can run past the end of the line.
    • Trailing empty field. With field = 3, ["a,b,", "c,a,z", "d,c,"] gives "a,b,\nd,c,\nc,a,z", because two lines have an empty third field. Without the -1 that input would throw.
    • Numbers as text. The field is compared as text, so "10" comes before "9".
    • Empty array. The result is "".
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free