1221. Equal-Length Word Sort
A library shelves short codes that all have the same length L. Sort the array words in ascending dictionary order and return the sorted array. Equal words stay together, and since the words are plain strings their relative order does not affect the output.
Use an LSD radix sort: for the character positions L - 1 down to 0, run a stable counting sort over the 26 letters on that position only. After the pass for position 0 the words are fully sorted. This takes O(n * L) time, which beats a comparison sort when the words are short but numerous.
Here 1 <= words.length <= 10^5, 1 <= L <= 10, every word has exactly L characters, and words use lowercase letters. The space needed is O(n) besides the output.
Example 1
- Input:
- words = ["dog","cat","cow","ant"]
- Output:
- ["ant","cat","cow","dog"]
- Explanation:
Sorting alphabetically gives ant, cat, cow, dog.
Example 2
- Input:
- words = ["bca","bac","abc","cab","acb","cba"]
- Output:
- ["abc","acb","bac","bca","cab","cba"]
- Explanation:
All six permutations of abc come out in dictionary order.
Example 3
- Input:
- words = ["zz","az","za","aa"]
- Output:
- ["aa","az","za","zz"]
- Explanation:
Words are ordered by the first letter and then by the second letter.
Constraints
1 ≤ words.length ≤ 105
all words have the same length L, 1 ≤ L ≤ 10
words contain lowercase letters only
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n * L)
- Space
- O(n)