Skip to the content

Sort by length

Problem

A crossword app keeps its words from shortest to longest, to find fast the ones that fit in a slot.

Write a function that takes a list of words and returns a new list sorted by length, from shortest to longest.

When two words are the same length, the one that comes first in the alphabet goes first: "cat" before "dog". They all arrive in lowercase. With an empty list you return an empty list.

Notice there are two rules, not one: the length decides, and the alphabet only breaks ties.

Examples

  • Different lengths

    ["basket", "cat", "table"] → ["cat", "table", "basket"]

  • All the same length

    ["fox", "cat", "dog"] → ["cat", "dog", "fox"]

  • Length and alphabet

    ["sun", "fish", "ant", "go"] → ["go", "ant", "sun", "fish"]

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def sort_by_length(words):
    pass

JavaScript

function sortByLength(words) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n log n) challenges

See all challenges →