Letters in the Noise

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
L5
Asked in
Quantiphi

Problem

A text-cleaning step in your pipeline needs a per-letter tally of the raw strings passing through it. For a given s, return the letter frequencies as [letter, count] pairs, ordered alphabetically by letter.

Case and punctuation are distractions. Find what each letter really weighs.

Example 1

Input:

s = "Hello World!"

Output:

[["d",1],["e",1],["h",1],["l",3],["o",2],["r",1],["w",1]]

Example 2

Input:

s = "aaBBcc"

Output:

[["a",2],["b",2],["c",2]]

Worked solution and explanation

What this really is

Strip the costume and this is a case-folded letter tally, the simplest frequency map there is. The real question is whether you build a keyed count at all: a set can tell you which letters appeared but throws the counts away, and a plain list cannot key by letter. You need a dictionary keyed by the lowercased character. The one move that actually separates answers is lowercasing each letter before it becomes a key, so 'A' and 'a' land in the same bucket. Skip it and your counts split across cases and your output carries uppercase keys the lowercase contract forbids.


Break down the requirements

Step 1: Lowercase before you key

Lowercase each alphabetic character so case-variants collapse into one bucket, and skip anything that is not a letter. The lowercasing has to happen before the character keys the map; do it afterward and the counts have already split into 'A' and 'a'.

Step 2: Count into a map

Tally into a dictionary keyed by the lowercase letter. One pass over the string, constant-time updates per character.

Step 3: Sort the keys, format the pairs

Walk the keys in sorted order and emit each as a [character, count] pair. Sorting the keys (at most 26 of them) is effectively free.


The solution

Frequency map with alphabetic filter and sorted output
def character_occurrence_map(s):
    counts = {}
    for char in s:
        if char.isalpha():
            lower_char = char.lower()
            counts[lower_char] = counts.get(lower_char, 0) + 1
    return [[key, counts[key]] for key in sorted(counts)]

Common follow-up questions