Start learning free

LESSON 22 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Sort V2 in Scala: Descending Order with sortWith

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -r flag baked in. Given a list of lines, return them sorted in descending order by character code (the exact reverse of v1's order, like LC_ALL=C sort -r: lowercase letters come before uppercase ones), joined by newline characters (\n). Duplicates are all kept. If the list is empty, return the empty string.

Function signature:

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

Example:

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

Output: "cherry\nbanana\napple"

When printed:
cherry
banana
apple

Use sortWith(_ > _) for descending order, then combine the lines with mkString("\n").

The full solution:
class Solution {
    def sortLines(lines: List[String]): String = {
        val sortedLines = lines.sortWith(_ > _)
        sortedLines.mkString("\n")
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Sort V2 in Scala, explained

    Problem overview

    Version 2 of the sort project adds the -r flag, which reverses the order. sortLines(lines: List[String]): String receives a List of lines and returns them in descending order by character code, joined by \n. Duplicates are kept, and an empty list gives the empty string.

    The result is the exact reverse of ascending order: lowercase letters now come before uppercase ones, and an empty line comes last. For ["banana", "apple", "cherry"] the answer is "cherry\nbanana\napple".

    Approach

    The default ordering gives ascending results, so you need to say "biggest first" instead. Scala's sortWith takes a function of two elements, (a, b), that returns true when a should be placed before b. Passing a function that answers "is a greater than b?" gives descending order.

    Another route is to sort ascending and then call reverse. That also works for this problem: for strings, reversing an ascending sort gives the same sequence as a descending sort. The lesson uses sortWith because it states the order directly in one call.

    Reading the comparison function

    The three forms below are equivalent. For List("banana", "apple", "cherry"), each one gives List(cherry, banana, apple):

    lines.sortWith((a, b) => a > b)
    lines.sortWith(_ > _)
    lines.sorted.reverse
    

    Swapping the operator flips the direction: lines.sortWith(_ < _) gives List(apple, banana, cherry), which is ascending order, the same as the previous version. The only thing sortWith asks of you is a yes-or-no answer to "should the first argument come first?"

    Step by step

    1. Create val sortedLines from lines.sortWith(_ > _). The underscores are shorthand: _ > _ means (a, b) => a > b, with the first underscore standing for the first argument and the second for the second.
    2. Return sortedLines.mkString("\n"). This is the last expression of the method, so its value is the method's result and no return is needed.

    The solution in Scala

    class Solution {
        def sortLines(lines: List[String]): String = {
            val sortedLines = lines.sortWith(_ > _)
            sortedLines.mkString("\n")
        }
    }
    

    Points worth knowing:

    • The comparison > on two strings compares them by character code, the same rule the ascending version relies on. So the lesson's order really is the mirror image of the previous one.
    • Lists are immutable. sortWith returns a new List and leaves lines untouched.
    • The parameter type is List[String] here, not Array[String]. sortWith and mkString work on both, so the body would look the same either way.

    Scala's collections offer three sorting methods, and it helps to know which does what. sorted uses the element type's default order. sortBy sorts by a key that a function computes from each element. sortWith takes a full comparison of two elements, which is the one to reach for when the order is not the default one, as it is here.

    Complexity

    Sorting n lines takes O(n log n) comparisons, each costing up to the length of the strings compared. The sorted copy and the joined string each use O(n) extra space.

    Edge cases and common mistakes

    • Case. ["apple", "Zebra", "banana"] gives "banana\napple\nZebra": lowercase words come first when the order is reversed.
    • Empty lines. ["b", "", "a"] gives "b\na\n". The empty line sorts last, so the result ends with a newline character.
    • Duplicates. ["b", "a", "b", "a"] gives "b\nb\na\na".
    • Numbers as text. ["10", "9", "1"] gives "9\n10\n1", because the lines are compared as text, character by character.
    • Empty list. The result is the empty string.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free