The Alphabet Sorter
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
Problem
Given a list of strings, return a dict whose keys are lowercase first characters and values are lists of strings starting with that character, preserving input order within each group.
Filing cabinet logic: everything goes in its proper drawer.
Example 1
Input:
strings = ["apple","ant","banana","avocado"]
Output:
{"a":["apple","ant","avocado"],"b":["banana"]}Example 2
Input:
strings = ["cat","cow","dog"]
Output:
{"c":["cat","cow"],"d":["dog"]}Worked solution and explanation
Why this problem exists in real interviews
Grouping strings by their initial character tests dictionary accumulation with key derivation. It is the same grouping pattern as GROUP BY in SQL, applied to the first character.
Break down the requirements
Step 1: Extract the first character, lowercased
Use word[0].lower() as the grouping key.
Step 2: Accumulate strings per group
Append each string to the list for its initial character, preserving input order.
The solution
def group_by_initial(strings):
groups = {}
for s in strings:
key = s[0].lower()
if key not in groups:
groups[key] = []
groups[key].append(s)
return groupsCommon follow-up questions
- What if the output keys should be sorted alphabetically? (Tests using `dict(sorted(groups.items()))` or building the dict in sorted-key order.)
- What if strings can be empty? (Tests guarding against `s[0]` on empty strings.)
- What if you needed a default dict for cleaner code? (Tests using `collections.defaultdict(list)` to eliminate the manual key check.)