Start learning free

LESSON 23 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Sort V3 in Scala: Numeric Order with sortBy and toInt

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -n flag baked in. Each input line is the string form of an integer that fits in 32 bits (an optional leading -, no leading +; leading zeros such as "007" are allowed). Sort the lines numerically (not lexicographically) in ascending order, and return the original strings joined by newlines (\n). Lines with the same numeric value keep their original relative order (a stable sort). The real sort -n would break such ties by comparing the text; this version does not. If the list is empty, return the empty string.

Note: lexicographic sort would put "100" before "20"; numeric sort puts 20 before 100.

Function signature:

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

Example:

Input: lines = ["100", "20", "3", "10"]

Output: "3\n10\n20\n100"

When printed:
3
10
20
100

Use sortBy(_.toInt) so the comparison happens on the integer value, then join the result with mkString.

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

STEP 1 OF 2
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Sort V3 in Scala, explained

    Problem overview

    Version 3 of the sort project adds -n, numeric sorting. Each line of sortLines(lines: Array[String]): String is the text of a 32-bit integer: an optional leading -, no +, and leading zeros such as "007" allowed. The method sorts the lines by numeric value, ascending, and returns the original strings joined by \n. An empty array gives the empty string.

    For ["100", "20", "3", "10"] the answer is "3\n10\n20\n100". Sorted as text, the same lines would give "10\n100\n20\n3", because "100" is compared character by character and '1' is smaller than '2'.

    When two lines have the same value, such as "7" and "007", they keep their original relative order. The real sort -n would settle such ties by comparing the text, but this version doesn't.

    Approach: sort by a key, return the original

    You want to order the strings by a number that is computed from each string, while keeping the strings themselves in the output. That is exactly what sortBy does: it takes a function that maps each element to a key, orders the elements by their keys, and returns the elements, not the keys. So the key function is _.toInt, which parses a line into an Int.

    Because "007" stays "007" in the output, the text of every line survives, leading zeros included. Only the comparison uses the parsed numbers.

    Step by step

    1. Create val sortedLines from lines.sortBy(_.toInt). The shorthand _.toInt means line => line.toInt.
    2. Return sortedLines.mkString("\n"), which places a newline between each two lines and none after the last.

    The solution in Scala

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

    Scala details to be aware of:

    • toInt on a string parses it as a decimal number. "007".toInt is 7 and "-0".toInt is 0, so leading zeros and a negative sign are handled for you.
    • A line that is not a number makes toInt throw a NumberFormatException. For the input ["1", "abc"] the message is For input string: "abc". The lesson guarantees valid integers, so you don't need to guard against it here.
    • Int is 32 bits, which is why the statement limits the values to that range. The extremes -2147483648 and 2147483647 parse and sort correctly: ["2147483647", "-2147483648", "0"] gives "-2147483648\n0\n2147483647".
    • sortBy is a stable sort: elements with equal keys stay in their original order. That is how the tie rule from the statement is met without any extra code.
    • The result of sortBy on an Array[String] is a new array, so lines is not modified.

    Complexity

    Sorting n lines takes O(n log n) comparisons of integers. The key function may run again for the same element during the sort, but each parse is short, so the overall bound stays the same. The sorted copy and the joined result take O(n) space.

    Edge cases and common mistakes

    • Sorting as text. Calling lines.sorted instead puts "100" before "20". The key function is what makes the order numeric.
    • Negative numbers. ["-5", "3", "-20", "0"] gives "-20\n-5\n0\n3". As text, "-5" would sort before "-20", which is wrong numerically.
    • Equal values. ["7", "007", "7", "07"] comes out unchanged, "7\n007\n7\n07", since all four lines equal 7. With ["007", "7"] the result is "007\n7": the original order wins, not the text.
    • Converting the lines first. Parsing every line to an Int and sorting those numbers would lose the original text, so "007" would print as 7. Sort the strings by a key instead.
    • 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