Feather Sort: By Length then Lexicographic
๐ฆ Feather Sort: By Length then Lexicographic
Difficulty: Beginner Tags: sorting, strings, multi-key sorting Series: CS 101
Problem
Sort a list of words with a twist: first by length (shortest to longest), then alphabetically if words have the same length!
This is called multi-level sorting or sorting by multiple keys.
Input
data = list[str] # List of words to sort
Output
list[str] # Sorted list (new list, don't modify original)
Constraints
- List can have up to 100,000 words
- All words contain only lowercase letters (a-z)
Examples
Example 1: Basic Sorting
Input: ['aa', 'b', 'ab']
Output: ['b', 'aa', 'ab']
Step-by-step: 1. Sort by length first: - 'b' has length 1 - 'aa' has length 2 - 'ab' has length 2
- For same-length words, sort alphabetically:
- Length 1: 'b' (only one word)
-
Length 2: 'aa' comes before 'ab' alphabetically
-
Result:
['b', 'aa', 'ab']
Example 2: Multiple Ties
Input: ['a', 'b', 'aa', 'ab']
Output: ['a', 'b', 'aa', 'ab']
Why? - Length 1: 'a' and 'b' โ alphabetically: 'a', 'b' - Length 2: 'aa' and 'ab' โ alphabetically: 'aa', 'ab'
Example 3: All Same Length
Input: ['dog', 'cat', 'bat', 'ant']
Output: ['ant', 'bat', 'cat', 'dog']
All words have length 3, so they're sorted purely alphabetically.
Example 4: All Different Lengths
Input: ['apple', 'cat', 'banana', 'a']
Output: ['a', 'cat', 'apple', 'banana']
Lengths: 1, 3, 5, 6 โ automatically sorted by length.
Output
Code execution results displayed hereโฆ
Test Results
Test results displayed hereโฆ