Start learning free

LESSON 21 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Sort in Kotlin: Ascending Order by Character Code

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:

fun sortLines(lines: Array<String>): String

Example:

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

Output: "apple\nbanana\ncherry"

When printed:
apple
banana
cherry

Convert the array into a mutable list, sort it in place with sort(), then combine it with joinToString("\n").

The full solution:
class Solution {
    fun sortLines(lines: Array<String>): String {
        val sortedLines = lines.toMutableList()
        sortedLines.sort()
        return sortedLines.joinToString("\n")
    }
}

STEP 1 OF 3
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Sort V1 in Kotlin, explained

    Problem overview

    The sort project starts with its simplest form. sortLines(lines: Array<String>): String takes the lines, sorts them in ascending order by character code, and returns them joined with \n. Duplicates stay, and an empty array gives the empty string.

    "By character code" means every character is compared by its numeric value. In that order every uppercase letter comes before every lowercase letter, so "Zebra" sorts before "apple", and an empty line comes first of all. For ["banana", "apple", "cherry"] the result is "apple\nbanana\ncherry".

    Approach

    Kotlin's standard library already knows how to order strings, so the work is three small moves: copy the input into a list you can reorder, sort that list, and glue the lines together. You don't write a sorting algorithm.

    The default order of String compares character by character, using each character's numeric code, and a shorter string that is a prefix of a longer one comes first. That is the order the lesson asks for, so plain sort() needs no comparator.

    Step by step

    1. Copy the array into a mutable list. lines.toMutableList() builds a new MutableList<String>. A MutableList can be sorted in place, and the original array stays untouched.
    2. Sort it in place. sortedLines.sort() reorders the list itself and returns nothing.
    3. Join with newlines. joinToString("\n") places the separator between lines only, so there is no newline after the last one.

    The solution in Kotlin

    class Solution {
        fun sortLines(lines: Array<String>): String {
            val sortedLines = lines.toMutableList()
            sortedLines.sort()
            return sortedLines.joinToString("\n")
        }
    }
    

    Kotlin details in this code

    • sort() against sorted(). On a MutableList, sort() changes the list and returns Unit. sorted() leaves the list alone and returns a new sorted List. This is why the solution calls sort() on its own line and then joins sortedLines. An equivalent one-liner is lines.sorted().joinToString("\n").
    • Why copy first. An Array has its own sort() that reorders it in place. Using the copy means the caller's array is not changed behind its back. After calling sortLines(arrayOf("b", "a")), the original array still reads [b, a].
    • The sort is stable, so equal lines keep their original relative order. For plain strings you can't see the difference, but it matters in later versions of the project, where lines that compare equal can still be different.
    • joinToString with an empty list returns "", so the empty case needs no special code.

    Complexity

    Sorting n lines takes O(n log n) comparisons, and each comparison costs up to the length of the shorter string. Copying and joining are O(n) in the number of lines. The extra space is the copied list plus the result string.

    Edge cases and common mistakes

    • Capitals first. ["apple", "Zebra", "", "banana", "apple"] gives the lines "", "Zebra", "apple", "apple", "banana". Don't try to make the sort case-insensitive; this lesson wants the raw character order.
    • Empty line first. The empty string is shorter than any other string with the same start, so it sorts before all of them. The joined result then begins with a newline.
    • Duplicates are kept. Sorting doesn't remove anything.
    • Empty array. The result is "".
    • Using the return value of sort(). Writing return lines.toMutableList().sort().joinToString("\n") doesn't compile, because sort() returns Unit, which has no joinToString.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free