Master a structured 5-step framework for algorithmic problem solving: understand the problem, explore concrete examples, break it down, solve or simplify, and look back to refactor.
A request to “count the characters in a string” leaves several decisions open. Does A count with a? Does a space count? Use one example to carry the same decisions from the problem statement into the code and its tests.
For this example, count English letters and digits, treating uppercase and lowercase letters as equal. Ignore punctuation, whitespace, and other characters. Return a mapping from each accepted character to its count. Return an empty mapping for a non-string input.
The word alphanumeric can mean different things in different languages. The explicit English-letter and digit rule makes the expected result the same in both versions below.
| Input | Expected counts | What it tests |
|---|---|---|
"Aa!" | a → 2 | Case and punctuation |
"B2 b2" | b → 2, 2 → 2 | Digits, repeats, and spaces |
"" or "!" | Empty mapping | No characters to count |
The number 42 | Empty mapping | Non-string input |
Start with an empty mapping. Visit each original character once. If it is an English letter or digit, convert it to lowercase and add one to its count. A missing entry starts at zero.
Trace "Aa!" by hand. The first letter creates the entry a → 1. The second updates it to a → 2. The final character leaves that count unchanged.
If the filtering rule is getting in the way, first count a string containing only lowercase letters. Once "aba" produces a → 2, b → 1, add filtering and run the mixed-input cases.
function charCount(text) {
const counts = {};
if (typeof text !== "string") return counts;
for (const character of text) {
if (!/[A-Za-z0-9]/.test(character)) continue;
const key = character.toLowerCase();
counts[key] = (counts[key] ?? 0) + 1;
}
return counts;
}Trace "éA2" before changing the filter. Both versions should return counts for a and 2. Checking the original character before converting case keeps this behavior consistent. Keep this example as a test if you extract the filter into a helper.
For input of length n, the loop uses O(n) time. The result has at most 36 keys, one per lowercase English letter or digit. With that fixed alphabet, even the result occupies O(1) entries. If the allowed alphabet can grow, report O(k) entries for k distinct characters.