Given a list of strings words, sort it in ascending order of string length (the total number of characters in each string) and return the sorted list.
When two strings have the same length, they must keep their relative order from the input. In other words, the sort must be stable.
Function Signature
def sort_by_length(words: list[str]) -> list[str]:
Rules
-
The length of a string is its number of characters. The empty string has length 0.
-
Strings of equal length appear in the output in the same order as in
words
. Do not break ties alphabetically.
-
Return a list that contains every input string exactly once, duplicates included.
Constraints
-
0 <= len(words) <= 10^4
-
0 <= len(words[i]) <= 100
-
words[i]
consists of printable ASCII characters.
Examples
Input: words = ["banana", "apple", "kiwi", "fig", "watermelon"]
Output: ["fig", "kiwi", "apple", "banana", "watermelon"]
The lengths are 6, 5, 4, 3 and 10, so ordering by length gives "fig" (3), "kiwi" (4), "apple" (5), "banana" (6) and "watermelon" (10).
Input: words = ["cat", "dog", "bird", "ox", "elephant"]
Output: ["ox", "cat", "dog", "bird", "elephant"]
"cat" and "dog" both have length 3. "cat" comes first in the input, so it stays first in the output.
Input: words = ["bb", "a", "", "aa", "c"]
Output: ["", "a", "c", "bb", "aa"]
The empty string has length 0 and goes first. "bb" stays ahead of "aa" because it appears earlier in the input, even though "aa" is smaller alphabetically.