Count Characters by First Appearance
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given an input string s, implement get_character_frequencies to compute the total occurrence count of every distinct character present in s.
Return a list of two-element pairs [character, count], ordered strictly by the index at which each character first appears when reading s from left to right:
- Case-sensitive: Uppercase and lowercase letters (such as
'M'and'm') count as separate characters. - Count every token: Spaces, digits, punctuation marks, control characters, and non-ASCII Unicode symbols are all counted just like letters—do not skip or filter any character.
- Empty input: When
sis"", return[].
def get_character_frequencies(s: str) -> List[List[object]]:
pass
Examples
Example 1
s = "radar"
# Output: [['r', 2], ['a', 2], ['d', 1]]
Walk-through: Reading left to right, 'r' is seen first (at indices 0 and 4), 'a' second (at indices 1 and 3), and 'd' third (at index 2).
Example 2
s = "MmNnM"
# Output: [['M', 2], ['m', 1], ['N', 1], ['n', 1]]
Walk-through: Uppercase 'M' and lowercase 'm' are distinct, as are 'N' and 'n'. The second 'M' at index 4 increments 'M''s count to 2 while keeping 'M' in the first output slot.
Example 3
s = "go 2 go?"
# Output: [['g', 2], ['o', 2], [' ', 2], ['2', 1], ['?', 1]]
Walk-through: Spaces (' '), digits ('2'), and punctuation ('?') are counted alongside letters, ordered by when each character first appeared.
Example 4
s = "***"
# Output: [['*', 3]]
Walk-through: Only '*' appears in s, repeated three times, yielding a single entry ['*', 3].
Constraints
0 <= len(s) <= 10^6smay contain arbitrary Unicode characters.- Target time complexity is
O(n), wheren = len(s).
Step-by-step walkthrough
Pin down every output rule
Given a string
s, we need to return[character, count]pairs ordered strictly by when each distinct character first appeared ins.Verify each requirement before coding:
- Earliest-appearance ordering: In
"radar",'r'appears first,'a'second, and'd'third — never sort alphabetically or by highest frequency. - Exact case distinction:
'M'and'm'are separate keys ("MmNnM"produces[['M', 2], ['m', 1], ['N', 1], ['n', 1]]). - Count every token: Whitespace, digits, punctuation, control characters, and Unicode symbols are all counted (
"go 2 go?"produces[['g', 2], ['o', 2], [' ', 2], ['2', 1], ['?', 1]]). - Empty input:
""returns[]. - Linear target: Since
len(s)can reach10^6, we need anO(n)single-pass algorithm.
- Earliest-appearance ordering: In
Why calling `s.count(ch)` inside a loop times out
A tempting first attempt scans
sand callss.count(ch)each time a new character appears:for each index i from 0 to n - 1: if s[i] was not seen in s[0 .. i - 1]: append [s[i], s.count(s[i])]Every
s.count(ch)call walks the entire string of lengthn. Withkdistinct Unicode characters ins, that executeskfull scans —O(n * k)work, which reachesO(n^2)(~10^12operations atn = 10^6) whenever most characters are unique.Instead of rescanning from scratch for each character, one left-to-right pass can accumulate all counts at once inside a lookup table.
Track counts and arrival order in one dictionary
A hash map (
dictin Python) maps each character to its running count withO(1)average lookup and update time.Better yet, since Python 3.7,
dictguarantees insertion order: keys remain in the exact sequence they were first inserted. Incrementing an existing key's count (counts[ch] += 1) updates its value in place without moving its slot:Input: "radar" Read 'r' (unseen) -> slots: [ 'r': 1 ] Read 'a' (unseen) -> slots: [ 'r': 1 | 'a': 1 ] Read 'd' (unseen) -> slots: [ 'r': 1 | 'a': 1 | 'd': 1 ] Read 'a' (seen!) -> slots: [ 'r': 1 | 'a': 2 | 'd': 1 ] <-- 'a' stays in slot 1 Read 'r' (seen!) -> slots: [ 'r': 2 | 'a': 2 | 'd': 1 ] <-- 'r' stays in slot 0(In languages whose default hash table is unordered, such as C++
std::unordered_map, you either use an ordered map like JavaLinkedHashMapor appendchto a companionfirst_seenlist inside the "unseen" branch.)Write the counting pass and output builder
We initialize an empty dictionary
counts, scan each characterchins, and then convertcounts.items()into[ch, count]two-element lists without sorting:counts: Dict[str, int] = {} for ch in s: if ch in counts: counts[ch] += 1 else: counts[ch] = 1 result: List[List[object]] = [] for ch, count in counts.items(): result.append([ch, count])Trace Example 1 and Example 3 step by step
Example 1: s = "radar" ch = 'r' -> insert -> counts = {'r': 1} ch = 'a' -> insert -> counts = {'r': 1, 'a': 1} ch = 'd' -> insert -> counts = {'r': 1, 'a': 1, 'd': 1} ch = 'a' -> increment -> counts = {'r': 1, 'a': 2, 'd': 1} ch = 'r' -> increment -> counts = {'r': 2, 'a': 2, 'd': 1} result -> [['r', 2], ['a', 2], ['d', 1]] Example 3: s = "go 2 go?" ch = 'g' -> {'g': 1} ch = 'o' -> {'g': 1, 'o': 1} ch = ' ' -> {'g': 1, 'o': 1, ' ': 1} ch = '2' -> {'g': 1, 'o': 1, ' ': 1, '2': 1} ch = ' ' -> {'g': 1, 'o': 1, ' ': 2, '2': 1} (' ' stays 3rd) ch = 'g' -> {'g': 2, 'o': 1, ' ': 2, '2': 1} ('g' stays 1st) ch = 'o' -> {'g': 2, 'o': 2, ' ': 2, '2': 1} ('o' stays 2nd) ch = '?' -> {'g': 2, 'o': 2, ' ': 2, '2': 1, '?': 1} result -> [['g', 2], ['o', 2], [' ', 2], ['2', 1], ['?', 1]]When
s = "", neither loop executes andresultreturns[].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def get_character_frequencies(s: str) -> List[List[object]]: # counts: dict mapping character -> total occurrences, e.g. {'r': 2, 'a': 2, 'd': 1}. # Python 3.7+ dicts preserve key insertion order, matching each character's earliest index. counts: Dict[str, int] = {} # Phase 1: scan `s` once to tally every character (case-sensitive, including whitespace/symbols) for ch in s: if ch in counts: # Updating an existing key raises its count without moving its slot in `counts` counts[ch] += 1 else: # First occurrence of `ch`: inserting now fixes its output position counts[ch] = 1 # Phase 2: pack the ordered (character, count) entries into [character, count] pairs without sorting result: List[List[object]] = [] for ch, count in counts.items(): result.append([ch, count]) return result✅ Submit now — all tests should pass.
Intuition & how it works
Picture greeting guests at a venue entrance with a blank sign-in sheet. The first time someone arrives, you write their name on the next blank line with 1 check mark. If that same guest steps out and returns later, you locate their existing line and add another check mark without moving their name down the page. When the doors close, reading the sheet top to bottom reports each guest's total visits in the exact order they first walked in.
Calling s.count(ch) each time you meet a new character rescans all n characters of s from index 0, costing O(n * k) time across k distinct characters — which degrades to O(n^2) (10^12 character comparisons when n = 10^6) on diverse Unicode inputs. Storing running totals in a hash map (a key-value lookup structure, dict in Python, with O(1) average lookup and update time) tallies every character in one left-to-right scan, while Python's built-in insertion order (keeping dictionary keys in the exact sequence they were first inserted) acts just like our sign-in sheet.
Trace s = "go g?":
- Read
'g'(index0): absent fromcounts, so insert'g': 1->{'g': 1}. - Read
'o'(index1): absent, so insert'o': 1->{'g': 1, 'o': 1}. - Read
' '(index2): absent, so insert' ': 1->{'g': 1, 'o': 1, ' ': 1}. - Read
'g'(index3): already present, so increment in place ->{'g': 2, 'o': 1, ' ': 1}('g'stays first). - Read
'?'(index4): absent, so insert'?': 1->[['g', 2], ['o', 1], [' ', 1], ['?', 1]].
Complexity
Let n be len(s) and k be the number of distinct characters in s (k <= n).
- Time: O(n) on average. We walk the
ncharacters ofsonce, performing oneO(1)average dictionary lookup and update per character, followed by anO(k)pass overcounts.items()to build the output pairs. - Space: O(k) auxiliary memory. Both
countsandresulthold one entry per distinct character (kentries total).
Edge cases
- Empty string (
""): Both loops perform zero iterations and return[]. - Single repeated symbol (Example 4,
"***"): Collapses into one entry[['*', 3]]. - All unique characters: Produces
nentries of count1in one linear pass. - Spaces, digits, punctuation, and control codes (Example 3,
"go 2 go?"):' ','2','?','\t', and'\n'are tallied identically to letters. - Mixed letter casing (Example 2,
"MmNnM"):'M'and'm'have distinct character codes and stay separate. - Unicode characters: Iterating
for ch in ssteps one Unicode code point (an individual numeric character identifier in the Unicode standard, such as'é'or'😀') at a time. Visually identical decomposed text ('e'followed by combining acute accent'\u0301') counts as two code points unless normalized beforehand viaunicodedata.normalize("NFC", s).
Common mistakes
- Sorting by count or character code: Calling
Counter(s).most_common()orsorted(counts.items())overwrites first-appearance order — on"banana",most_common()puts'a'(3) ahead of'b'(1), even though'b'appeared first. - Tracking seen characters in a
setwithout an ordered list: Iterating over a Pythonsetyields arbitrary hash order rather than arrival order. - Skipping non-letters with
ch.isalpha(): Drops spaces, digits, and punctuation required by the specification. - Repeatedly calling
s.count(ch): Inflates runtime fromO(n)toO(n * k)(worst-caseO(n^2)). - Folding case with
.lower(): Merges'M'and'm', violating case sensitivity.
Alternative approaches
collections.Counter(s): BecauseCountersubclassesdictin Python 3.7+,[[ch, cnt] for ch, cnt in Counter(s).items()]also preserves first-appearance order inO(n)time (just avoid.most_common()).- Hash map paired with an explicit
orderlist: In languages with unordered hash tables (such as C++std::unordered_mapor Gomap), appendchto anorderarray the first timechis inserted, then iterate overorderto emit[ch, counts[ch]].
Follow-up questions
- How would you adjust the implementation so uppercase and lowercase variants merge into a single count? Convert each character using
key = ch.casefold()— which performs Unicode case folding (mapping letters into a canonical caseless representation, such as'M' -> 'm'and'ß' -> "ss") — and count bykey. If the returned label should display whichever casing appeared earliest ins(for instance'M'in"MmNnM"), recorddisplay_char[key] = chwhenkeyis first inserted; otherwise emit[key, count]directly.
python
def get_character_frequencies_caseless(s: str):
counts = {}
display_char = {}
for ch in s:
key = ch.casefold()
if key in counts:
counts[key] += 1
else:
counts[key] = 1
display_char[key] = ch
return [[display_char[key], count] for key, count in counts.items()]
- Suppose inputs contain only 7-bit ASCII characters and RAM is tight; how can you minimize auxiliary memory while keeping first-seen order? ASCII (a 7-bit character standard assigning integers
0through127to basic English letters, digits, punctuation, and control codes) spans only128possible code points, so replace the hash table with a fixed integer arraycounts = [0] * 128indexed byord(ch). To emit pairs in first-appearance order without storing a separateorderlist, scansa second time: whenevercounts[ord(ch)] > 0, append[ch, counts[ord(ch)]]and resetcounts[ord(ch)] = 0so subsequent copies ofchare ignored (O(n)time,O(1)auxiliary space of128integers).
python
def get_ascii_frequencies_compact(s: str):
counts = [0] * 128
for ch in s:
counts[ord(ch)] += 1
result = []
for ch in s:
code = ord(ch)
if counts[code] > 0:
result.append([ch, counts[code]])
counts[code] = 0 # prevent emitting the same ASCII character twice
return result
- What changes if the text arrives as an unbounded byte or character stream that cannot be loaded into memory all at once? Our single-pass dictionary already processes data incrementally: read fixed-size chunks (for example
64 KBper read) and update the samecountsdictionary across chunks, bounding memory byO(k)(distinct characters) rather thanO(n)(stream length). When the input is raw UTF-8 bytes, decode chunks with an incremental decoder (a stateful decoder such ascodecs.getincrementaldecoder("utf-8")()that holds partial multi-byte UTF-8 sequences across chunk boundaries instead of raising decode errors). Across distributed workers, have each shard emit(character, local_count, earliest_global_offset)so a coordinator can sumlocal_countand sort thekdistinct characters bymin(earliest_global_offset).
Follow-up questions
- How would you adjust the implementation so uppercase and lowercase variants merge into a single count?
- Suppose inputs contain only 7-bit ASCII characters and RAM is tight; how can you minimize auxiliary memory while keeping first-seen order?
- What changes if the text arrives as an unbounded byte or character stream that cannot be loaded into memory all at once?
Similar questions
- Longest Duplicate-Free Substring
- Backend Java and Spring Framework Essentials
- Spring Payment Strategy Service Design
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses