Shortest Words First

EasySorting & Searching

Problem

A word-game app shows its dictionary with the shortest words at the top. Words of the same length appear in alphabetical order.

Given a list of lowercase words words, return them in that display order. Duplicate words are kept.

Example 1

Input:
words = ["pear", "fig", "apple", "kiwi", "date"]
Output:
["fig", "date", "kiwi", "pear", "apple"]

Length 3: fig. Length 4: date, kiwi, pear alphabetically. Length 5: apple.

Example 2

Input:
words = ["b", "a", "b"]
Output:
["a", "b", "b"]

Constraints

  • 0 ≤ words.length ≤ 10^4
  • 1 ≤ words[i].length ≤ 30
  • words[i] contains only lowercase English letters.

Hint

Show the first hint

Two rules: one for different lengths, one for equal lengths.

Walkthrough

How to approach it

01Clarify before coding

  • Is the alphabetical order plain character order? Yes, all words are lowercase a–z.
  • Are duplicates removed? No, every occurrence stays.
  • Can the list be empty? Yes.

02Brute force

Bucket words by length, sort each bucket alphabetically, then concatenate buckets from shortest to longest.

Cost: O(n log n · L) time for n words of length up to L: fine, but more code than one keyed sort.

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.

This problem is part of Pro.