Start learning free

LESSON 21 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort in Go: Alphabetical Order with sort.Strings

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:

func sortLines(lines []string) string

Example:

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

Output: "apple\nbanana\ncherry"

When printed:
apple
banana
cherry

Copy the slice so you don't reorder the caller's data, sort it with sort.Strings, then combine the lines with strings.Join using "\n".

The full solution:
func sortLines(lines []string) string {
    sortedLines := append([]string{}, lines...)
    sort.Strings(sortedLines)
    return strings.Join(sortedLines, "\n")
}

STEP 1 OF 4
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Sort V1 in Go, explained

    Problem overview

    This is the first version of a small sort command. The function sortLines takes a slice of strings and returns them in ascending order, joined by "\n". Duplicates are all kept, and an empty slice gives the empty string.

    The order is by character code, like LC_ALL=C sort. In that order every uppercase letter comes before every lowercase one, and an empty line comes before everything else. The example ["banana", "apple", "cherry"] becomes "apple\nbanana\ncherry".

    Approach: copy, sort, join

    Go's standard library does the hard part. sort.Strings sorts a []string in ascending order, comparing strings byte by byte. For ASCII text that is exactly "by character code", so no custom comparison is needed.

    One thing needs care: sort.Strings sorts in place. A slice is a small header pointing at an array, so the caller's slice and the one you receive share the same elements. Sorting lines directly would reorder the caller's data as a side effect. The function therefore sorts a copy.

    The last step turns the slice into one string. strings.Join places the separator between elements only, so there is no trailing newline.

    Step by step

    1. Write the signature sortLines(lines []string) string with its closing brace.
    2. Make a copy named sortedLines by appending all of lines to a new, empty slice. The trailing ... spreads a slice into separate arguments, so append adds every element.
    3. Sort the copy in place with sort.Strings.
    4. Join with "\n" and return the result.

    The solution in Go

    func sortLines(lines []string) string {
        sortedLines := append([]string{}, lines...)
        sort.Strings(sortedLines)
        return strings.Join(sortedLines, "\n")
    }
    

    The details that matter:

    • Why the copy is needed. Assigning one slice to another does not copy elements. With orig := []string{"c", "a", "b"} and alias := orig, calling sort.Strings(alias) leaves orig printing as [a b c]. Appending onto a fresh empty slice allocates new storage, so sorting it leaves lines as it was.
    • append([]string{}, lines...) is a common idiom for cloning a slice. The empty literal supplies a new array, and lines... passes every element as a separate argument.
    • The imports. The function uses the sort and strings packages. Go reports an unused import as an error, so import only what the code calls.
    • Empty input. Copying an empty slice gives an empty slice, sorting it does nothing, and strings.Join of an empty slice returns "", which is the required result.

    Complexity

    Time: O(n log n) comparisons for n lines, from the sort. Each comparison can cost up to the length of the strings compared, so the true cost also depends on how long the lines are. Copying and joining are O(n) in the number of lines.

    Space: O(n). The copy holds n string headers, and the joined result is a new string as long as all the lines together. The sort itself works in place.

    Edge cases and common mistakes

    • Uppercase before lowercase. ["apple", "Zebra"] sorts to "Zebra\napple", because Z has a smaller code than a. Sorting case-insensitively would be a different tool.
    • Empty lines come first. ["b", "", "a"] gives "\na\nb", so the output starts with a newline.
    • Duplicates stay. ["b", "a", "b"] gives "a\nb\nb". Sorting is not de-duplicating.
    • A prefix sorts first. ["app", "apple", "ap"] gives "ap\napp\napple": a shorter string that is a prefix of a longer one is smaller.
    • Sorting the input directly. It passes the examples but reorders the caller's slice, which can surprise any code that still uses it.
    • Expecting a trailing newline. strings.Join adds none after the last line.

    Testing

    • ["banana", "apple", "cherry"] gives "apple\nbanana\ncherry".
    • ["apple", "Zebra"] gives "Zebra\napple".
    • ["b", "", "a"] gives "\na\nb".
    • ["b", "a", "b"] gives "a\nb\nb".
    • ["app", "apple", "ap"] gives "ap\napp\napple".
    • An empty slice gives "".
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free