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 i where string[i] == char contributes 1 to 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 string is empty ("") or char never occurs in string, return 0.

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^5
  • len(char) == 1
  • string and char may include ASCII letters, digits, whitespace, punctuation, and general Unicode characters.

Step-by-step walkthrough

  1. Understand the input, output, and matching rules

    We receive string (any text, possibly empty) and char (a single target symbol), and we need to return an int equal to the number of positions in string that match char.

    Three rules govern every case:

    • Exact case matching: Uppercase and lowercase letters are separate symbols, so 'l' matches index 4 of "Levels" (1 match), not uppercase 'L' at index 0.
    • Tally every matching index: Back-to-back repeats are counted individually, so 'e' in "coffee" gives 2.
    • Zero when absent or empty: If char is nowhere in string—or if string is ""—the result is 0.
  2. 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 all N positions in the worst case—skipping even a single index could miss a match located there.

    Walking string once 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's string.count(char) also works when len(char) == 1, writing out the explicit loop makes the exact character-by-character check obvious in an interview.

  3. Trace the scan character by character

    Watch how the running counter match_count updates 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 1
    

    When string = "", the loop body runs zero times and match_count immediately returns 0.

  4. Write the counting loop

    Start match_count = 0 before iterating and test current_char == char directly:

    • 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
    
  5. 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':

  1. Initialize match_count = 0.
  2. Index 0 is 'L': 'L' == 'l' evaluates to False because uppercase and lowercase differ (match_count stays 0).
  3. Indices 1..3 ('e', 'v', 'e') all compare False (match_count stays 0).
  4. Index 4 is 'l': 'l' == 'l' evaluates to True, incrementing match_count to 1.
  5. Index 5 is 's': 's' == 'l' evaluates to False, so 1 is returned.

Complexity

Let N be the number of characters in string.

  • Time: O(N), because we visit each of the N positions in string once and perform a single O(1) character equality check per step.
  • Space: O(1) extra memory, because we only keep the integer match_count and loop variable current_char without copying or slicing string.

Edge cases

  • Empty string (""): The for loop executes zero iterations and returns 0 right away.
  • Target never appears: match_count stays 0 throughout the loop (Example 4: "glacier" with 'x').
  • Uppercase vs. lowercase: 'A' and 'a' have distinct code points, so "AaAa" returns 2 for 'A' and 2 for 'a'.
  • Adjacent repeats and single-character runs: "coffee" with 'e' returns 2, and "zzzzz" with 'z' returns 5 because 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 via unicodedata.normalize("NFC", ...).

Common mistakes

  • Folding case with .lower() or .upper(): Changing letter case makes "Levels" return 2 for 'l' instead of 1, breaking the case-sensitive rule.
  • Using unescaped regular expressions: Calling len(re.findall(char, string)) overcounts or crashes whenever char is a regex metacharacter—for instance, char = "." matches every character in "a.b.c" (5 instead of 2), and char = "[" raises an exception.
  • Counting contiguous groups instead of positions: Collapsing consecutive runs makes "aaabaaa" with 'a' return 2 groups instead of 6 occurrences.
  • Building collections.Counter(string) for a single lookup: Populating a hash map of every distinct character takes O(K) extra space and hashing overhead when one integer counter suffices.
  • Assuming str.count(char) behaves identically on an empty char: If a caller ever passed char = "", "abc".count("") returns 4 (counting empty boundaries around characters), whereas iterating for current_char in string returns 0 because each yielded element has length 1.

Alternative approaches

  • Built-in string.count(char): In CPython, string.count(char) scans the underlying character buffer in C in O(N) time and O(1) space; mention it in an interview after writing the explicit loop (and verify len(char) == 1 if 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 in O(N) time and O(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 string once to populate a frequency map (counts = collections.Counter(string)) in O(N) time and O(K) space for K distinct symbols, answering each counts.get(char, 0) lookup in O(1) time. If queries also ask for slice counts on string[left:right], precompute a prefix sum array per queried character—an array prefix where prefix[i] records how many times char appeared in the first i characters—so any substring query reduces to prefix[right] - prefix[left] in O(1) time, or store sorted index lists per character and binary-search left and right in O(log N) time with O(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 compute string.casefold().count(char.casefold()) after confirming char is 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 Python for loops 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 as df["text"].str.count(re.escape(char)) in pandas (or pl.col("text").str.count_matches(char, literal=True) in Polars). Wrapping char in re.escape(char) for pandas is critical because Series.str.count interprets its pattern as a regular expression, and chaining .fillna(0).astype(int) safely handles missing NaN entries.

Follow-up questions

Similar questions

More Discord interview questions

All 15 Discord questions →