Single-Character Occurrence Count
Medium · Coding & Algorithms · Data Scientist · Technical Screen
Problem Statement
Write a function number_of_character(string: str, char: str) -> int that computes how many positions in string hold the exact character char.
Your implementation must follow these matching rules:
- Exact case matching: Treat uppercase and lowercase letters as distinct symbols (for instance,
'L'and'l'do not match). - Position-by-position tally: Every index
iwherestring[i] == charcontributes1to the total, even when identical characters sit right next to one another. - Literal comparison: Spaces, digits, punctuation marks (such as
'.'or'?'), and non-ASCII Unicode symbols are compared as literal characters with no wildcard semantics. - Absent target or empty text: When
stringis empty ("") orcharnever occurs instring, return0.
Examples
Example 1
Input: string = "coffee", char = "e"
Output: 2
Both 'e' characters at indices 4 and 5 match the target, so consecutive repeats are counted separately for a total of 2.
Example 2
Input: string = "Levels", char = "l"
Output: 1
Index 0 contains uppercase 'L', which does not match lowercase 'l'. Only index 4 matches, producing 1.
Example 3
Input: string = "pepperoni", char = "p"
Output: 3
The character 'p' appears at index 0, index 2, and index 3, giving 3 total occurrences.
Example 4
Input: string = "glacier", char = "x"
Output: 0
No character in "glacier" equals 'x', so the function returns 0.
Constraints
0 <= len(string) <= 10^5len(char) == 1stringandcharmay include ASCII letters, digits, whitespace, punctuation, and general Unicode characters.
Step-by-step walkthrough
Understand the input, output, and matching rules
We receive
string(any text, possibly empty) andchar(a single target symbol), and we need to return anintequal to the number of positions instringthat matchchar.Three rules govern every case:
- Exact case matching: Uppercase and lowercase letters are separate symbols, so
'l'matches index4of"Levels"(1match), not uppercase'L'at index0. - Tally every matching index: Back-to-back repeats are counted individually, so
'e'in"coffee"gives2. - Zero when absent or empty: If
charis nowhere instring—or ifstringis""—the result is0.
- Exact case matching: Uppercase and lowercase letters are separate symbols, so
Why a single left-to-right scan is optimal
For a one-off query on an unindexed string of length
N, any correct algorithm must inspect allNpositions in the worst case—skipping even a single index could miss a match located there.Walking
stringonce from left to right with one integer accumulator checks each position once (O(N)time) and uses only one counter variable (O(1)extra space), with no temporary lists or hash maps. Although Python'sstring.count(char)also works whenlen(char) == 1, writing out the explicit loop makes the exact character-by-character check obvious in an interview.Trace the scan character by character
Watch how the running counter
match_countupdates across Example 1 ("coffee",'e') and Example 2 ("Levels",'l'):Trace 1: string = "coffee", char = 'e' index 0 1 2 3 4 5 current_char 'c' 'o' 'f' 'f' 'e' 'e' == 'e'? no no no no YES YES match_count 0 0 0 0 1 2 --> returns 2 Trace 2: string = "Levels", char = 'l' index 0 1 2 3 4 5 current_char 'L' 'e' 'v' 'e' 'l' 's' == 'l'? no no no no YES no match_count 0 0 0 0 1 1 --> returns 1When
string = "", the loop body runs zero times andmatch_countimmediately returns0.Write the counting loop
Start
match_count = 0before iterating and testcurrent_char == chardirectly:- Never call
.lower()or.upper()on either argument, because letter case must match exactly. - Plain
==compares literal characters, so spaces (' ') and punctuation ('.') behave like any ordinary letter rather than pattern wildcards.
def number_of_character(string: str, char: str) -> int: # match_count: running total of indices where the character equals `char`. # Initializing at 0 naturally returns 0 when `string` is empty or has no matches. match_count = 0 # Inspect each character one by one so adjacent repeats (like "ee") are all tallied. for current_char in string: # Direct == compares exact characters: case-sensitive ('l' != 'L') and literal ('.' == '.'). if current_char == char: match_count += 1 return match_count- Never call
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def number_of_character(string: str, char: str) -> int: # match_count: running total of indices where the character equals `char`. # Initializing at 0 naturally returns 0 when `string` is empty or has no matches. match_count = 0 # Inspect each character one by one so adjacent repeats (like "ee") are all tallied. for current_char in string: # Direct == compares exact characters: case-sensitive ('l' != 'L') and literal ('.' == '.'). if current_char == char: match_count += 1 return match_count✅ Submit now — all tests should pass.
Intuition & how it works
Picture sliding your finger from left to right underneath each character of string while holding a tally clicker initialized to 0. Whenever the symbol under your finger is an exact match for char, you click once to add 1; otherwise you advance straight to the next position. Once your finger reaches the end of the text, the number on the clicker is the final frequency.
Overcomplicating this scan introduces subtle bugs or unnecessary overhead. Converting case causes 'L' to be miscounted as 'l', building a full frequency map allocates memory for every unrelated symbol in string, and reaching for a regular expression—a pattern-matching mini-language where symbols such as '.' or '?' act as special wildcards—silently miscounts punctuation unless escaped. A plain for loop with == handles letters, spaces, punctuation, and empty text cleanly in constant memory.
Walk through string = "Levels" with char = 'l':
- Initialize
match_count = 0. - Index
0is'L':'L' == 'l'evaluates toFalsebecause uppercase and lowercase differ (match_countstays0). - Indices
1..3('e','v','e') all compareFalse(match_countstays0). - Index
4is'l':'l' == 'l'evaluates toTrue, incrementingmatch_countto1. - Index
5is's':'s' == 'l'evaluates toFalse, so1is returned.
Complexity
Let N be the number of characters in string.
- Time:
O(N), because we visit each of theNpositions instringonce and perform a singleO(1)character equality check per step. - Space:
O(1)extra memory, because we only keep the integermatch_countand loop variablecurrent_charwithout copying or slicingstring.
Edge cases
- Empty string (
""): Theforloop executes zero iterations and returns0right away. - Target never appears:
match_countstays0throughout the loop (Example 4:"glacier"with'x'). - Uppercase vs. lowercase:
'A'and'a'have distinct code points, so"AaAa"returns2for'A'and2for'a'. - Adjacent repeats and single-character runs:
"coffee"with'e'returns2, and"zzzzz"with'z'returns5because every index is checked independently. - Whitespace and punctuation: Spaces
' 'and punctuation such as'.'are compared literally with==, with no wildcard interpretation. - Accented Unicode symbols: Python strings iterate over Unicode code points—the numeric identifiers assigned to text characters—so a precomposed
'é'(U+00E9) differs from'e'followed by a combining accent (U+0301); if raw text can mix both forms, normalize both inputs first viaunicodedata.normalize("NFC", ...).
Common mistakes
- Folding case with
.lower()or.upper(): Changing letter case makes"Levels"return2for'l'instead of1, breaking the case-sensitive rule. - Using unescaped regular expressions: Calling
len(re.findall(char, string))overcounts or crashes whenevercharis a regex metacharacter—for instance,char = "."matches every character in"a.b.c"(5instead of2), andchar = "["raises an exception. - Counting contiguous groups instead of positions: Collapsing consecutive runs makes
"aaabaaa"with'a'return2groups instead of6occurrences. - Building
collections.Counter(string)for a single lookup: Populating a hash map of every distinct character takesO(K)extra space and hashing overhead when one integer counter suffices. - Assuming
str.count(char)behaves identically on an emptychar: If a caller ever passedchar = "","abc".count("")returns4(counting empty boundaries around characters), whereas iteratingfor current_char in stringreturns0because each yielded element has length1.
Alternative approaches
- Built-in
string.count(char): In CPython,string.count(char)scans the underlying character buffer in C inO(N)time andO(1)space; mention it in an interview after writing the explicit loop (and verifylen(char) == 1if inputs are untrusted). - Generator expression
sum(1 for ch in string if ch == char): A compact Pythonic form of the explicit loop that still runs inO(N)time andO(1)space.
Follow-up questions
- How would you preprocess a static string to answer many single-character or substring-slice frequency queries quickly? If callers query many different target characters across the whole string, scan
stringonce to populate a frequency map (counts = collections.Counter(string)) inO(N)time andO(K)space forKdistinct symbols, answering eachcounts.get(char, 0)lookup inO(1)time. If queries also ask for slice counts onstring[left:right], precompute a prefix sum array per queried character—an arrayprefixwhereprefix[i]records how many timescharappeared in the firsticharacters—so any substring query reduces toprefix[right] - prefix[left]inO(1)time, or store sorted index lists per character and binary-searchleftandrightinO(log N)time withO(N)total space. - What changes are needed to support case-insensitive matching across full Unicode text? For ASCII-only English text, comparing
current_char.lower() == char.lower()works cleanly. Across international Unicode text,.casefold()is the standard transformation for caseless matching, though certain characters expand to multiple code points when case-folded (for example, German'ß'.casefold()becomes"ss"), so computestring.casefold().count(char.casefold())after confirmingcharis non-empty. - How would you compute this character count across millions of rows in a columnar table or DataFrame without a Python row loop? Avoid
.apply()or Pythonforloops over rows and use a vectorized operation—a column-wide computation executed in compiled C/Rust/Cython code across an entire array at once—such asdf["text"].str.count(re.escape(char))in pandas (orpl.col("text").str.count_matches(char, literal=True)in Polars). Wrappingcharinre.escape(char)for pandas is critical becauseSeries.str.countinterprets its pattern as a regular expression, and chaining.fillna(0).astype(int)safely handles missingNaNentries.
Follow-up questions
- How would you preprocess a static string to answer many single-character or substring-slice frequency queries quickly?
- What changes are needed to support case-insensitive matching across full Unicode text?
- How would you compute this character count across millions of rows in a columnar table or DataFrame without a Python row loop?
Similar questions
- Concurrent Multi-Room TCP Chat Server with Python asyncio
- Streaming Per-User Session Aggregator
- Words Unique to Either Message
- Engineering Workflow for AI-Assisted Coding Interviews
- Persistent Multi-Room Chat Server over Raw TCP
- Redis Lease-Based Distributed Leader Election
More Discord interview questions
- Concurrent Multi-Room TCP Chat Server with Python asyncio Medium
- Persistent Multi-Room Chat Server over Raw TCP Medium
- Engineering Workflow for AI-Assisted Coding Interviews Medium Pro
- Redis Lease-Based Distributed Leader Election Medium Pro
- Experimentation Plan for Propensity-Targeted Subscription Pushes Medium Pro
- Driving a Business Decision with Causal Inference Medium Pro
- Streaming Per-User Session Aggregator Hard Pro
- Words Unique to Either Message Medium Pro
- Career Arc, Storage Project, and Production On-Call Hard Pro
- Experiment Design for Subscription Prompts and Friend Autocomplete Medium Pro