Problem 424739 · medium · Level 04 Non-Linear Data Structures

Sort Words by Length, Then Alphabet

divide and conquer · merge sort · strings · sort keys

A crossword setter wants a word list arranged with the shortest words first; words of the same length go alphabetically. Write arrange(words) returning a new list arranged that way, implemented as a recursive merge sort (do not call sorted or list.sort). Compare words with Python's normal string ordering.

Examples

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

Input:  words = []
Output: []

Constraints

  • 0 <= len(words) <= 5000, each word at most 20 lowercase letters.
  • Recursion depth is about log2(n).

Goals

  • Implement merge sort by hand on a list of strings
  • Compare on a composite key (length, then spelling)
  • Keep the merge stable so equal keys stay in their original order
Starting Python…