Start learning free

LESSON 21 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Sort V1 in Scala: Alphabetical Order with sorted and mkString

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:

def sortLines(lines: Array[String]): String

Example:

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

Output: "apple\nbanana\ncherry"

When printed:
apple
banana
cherry

Call sorted on the array to get a new sorted array (the original is left alone), then join it with mkString("\n").

The full solution:
class Solution {
    def sortLines(lines: Array[String]): String = {
        val sortedLines = lines.sorted
        return sortedLines.mkString("\n")
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Sort V1 in Scala, explained

    Problem overview

    The first version of the sort project is small. sortLines(lines: Array[String]): String receives an array of lines and returns them in ascending order, joined by \n. Duplicates are kept, and an empty array gives the empty string.

    The order is by character code, like LC_ALL=C sort. That means every uppercase letter comes before every lowercase letter, so "Zebra" sorts before "apple", and an empty line sorts first of all. For ["banana", "apple", "cherry"] the answer is "apple\nbanana\ncherry".

    Approach

    Scala's standard library already knows how to order strings, so the job has two parts: sort, then join. lines.sorted sorts using the default ordering of the element type, and for String that ordering compares the characters' codes one by one. A shorter string that is a prefix of a longer one comes first, which is why the empty string leads.

    What "by character code" means

    Every Char has a numeric code. 'Z' is 90 and 'a' is 97, so any capital letter is smaller than any lowercase one. To compare two strings, Scala looks at the first position where they differ and orders them by the codes found there. If one string runs out first, it is the smaller one: "app" comes before "apple", and "" comes before everything.

    This is the same rule the sort command applies when it runs in the plain C locale, and it is the reason the lesson's examples place "Zebra" ahead of "apple". Because the rule is the default ordering of String, you don't write any comparison yourself in this version.

    Step by step

    1. Create a val sortedLines from lines.sorted. The call returns a new array and leaves lines as it was, so you don't copy anything yourself.
    2. Join the sorted lines with mkString("\n"). The argument goes between neighbouring elements only, so there is no trailing newline after the last line.

    The solution in Scala

    class Solution {
        def sortLines(lines: Array[String]): String = {
            val sortedLines = lines.sorted
            return sortedLines.mkString("\n")
        }
    }
    

    Details that matter here:

    • sorted needs no comparison function because String has a built-in ordering. It works the same way for numbers, where it would order by value.
    • Sorting strings is not sorting numbers. The lines ["10", "9", "1"] come out as "1\n10\n9", because "10" is compared character by character and its first character '1' is smaller than '9'.
    • The method does not change its argument. After the call, an input array holding c, a, b still holds c, a, b.
    • mkString on an empty array returns "", which is exactly what the statement asks for the empty case, so no special handling is needed.

    Complexity

    Sorting n lines takes O(n log n) comparisons, and each comparison costs up to the length of the strings involved. The sorted copy needs O(n) extra space, and so does the joined result.

    Edge cases and common mistakes

    • Capitals first. ["apple", "Zebra", "banana"] gives "Zebra\napple\nbanana". This is correct for this lesson, even though a dictionary would put "Zebra" last.
    • Empty lines. ["b", "", "a"] gives "\na\nb": the empty line sorts first, so the result starts with a newline.
    • Duplicates. ["b", "a", "b", "a"] gives "a\na\nb\nb"; nothing is removed.
    • 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