# The Alphabet Sorter

> Filing cabinet logic: everything goes in its proper drawer.

Canonical URL: <https://datadriven.io/problems/the_alphabet_sorter>

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.

## 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

**Dict accumulation grouped by lowercased initial character**

```python
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 groups
```

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the number of strings. Each string is processed once.
> 
> **Space:** O(n) since every string appears in exactly one group.

> **Interviewers Watch For**
>
> Lowercasing the key to ensure case-insensitive grouping while preserving the original string in the group list.

> **Common Pitfall**
>
> Not lowercasing the key, which would separate 'Apple' (key 'A') from 'avocado' (key 'a') into different groups.

---

## Common 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.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_alphabet_sorter)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.