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 s is "", 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^6
  • s may contain arbitrary Unicode characters.
  • Target time complexity is O(n), where n = len(s).

Step-by-step walkthrough

  1. 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 in s.

    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 reach 10^6, we need an O(n) single-pass algorithm.
  2. Why calling `s.count(ch)` inside a loop times out

    A tempting first attempt scans s and calls s.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 length n. With k distinct Unicode characters in s, that executes k full scans — O(n * k) work, which reaches O(n^2) (~10^12 operations at n = 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.

  3. Track counts and arrival order in one dictionary

    A hash map (dict in Python) maps each character to its running count with O(1) average lookup and update time.

    Better yet, since Python 3.7, dict guarantees 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 Java LinkedHashMap or append ch to a companion first_seen list inside the "unseen" branch.)

  4. Write the counting pass and output builder

    We initialize an empty dictionary counts, scan each character ch in s, and then convert counts.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])
    
  5. 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 and result returns [].

  6. 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?":

  1. Read 'g' (index 0): absent from counts, so insert 'g': 1 -> {'g': 1}.
  2. Read 'o' (index 1): absent, so insert 'o': 1 -> {'g': 1, 'o': 1}.
  3. Read ' ' (index 2): absent, so insert ' ': 1 -> {'g': 1, 'o': 1, ' ': 1}.
  4. Read 'g' (index 3): already present, so increment in place -> {'g': 2, 'o': 1, ' ': 1} ('g' stays first).
  5. Read '?' (index 4): 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 n characters of s once, performing one O(1) average dictionary lookup and update per character, followed by an O(k) pass over counts.items() to build the output pairs.
  • Space: O(k) auxiliary memory. Both counts and result hold one entry per distinct character (k entries 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 n entries of count 1 in 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 s steps 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 via unicodedata.normalize("NFC", s).

Common mistakes

  • Sorting by count or character code: Calling Counter(s).most_common() or sorted(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 set without an ordered list: Iterating over a Python set yields 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 from O(n) to O(n * k) (worst-case O(n^2)).
  • Folding case with .lower(): Merges 'M' and 'm', violating case sensitivity.

Alternative approaches

  • collections.Counter(s): Because Counter subclasses dict in Python 3.7+, [[ch, cnt] for ch, cnt in Counter(s).items()] also preserves first-appearance order in O(n) time (just avoid .most_common()).
  • Hash map paired with an explicit order list: In languages with unordered hash tables (such as C++ std::unordered_map or Go map), append ch to an order array the first time ch is inserted, then iterate over order to 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 by key. If the returned label should display whichever casing appeared earliest in s (for instance 'M' in "MmNnM"), record display_char[key] = ch when key is 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 0 through 127 to basic English letters, digits, punctuation, and control codes) spans only 128 possible code points, so replace the hash table with a fixed integer array counts = [0] * 128 indexed by ord(ch). To emit pairs in first-appearance order without storing a separate order list, scan s a second time: whenever counts[ord(ch)] > 0, append [ch, counts[ord(ch)]] and reset counts[ord(ch)] = 0 so subsequent copies of ch are ignored (O(n) time, O(1) auxiliary space of 128 integers).

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 KB per read) and update the same counts dictionary across chunks, bounding memory by O(k) (distinct characters) rather than O(n) (stream length). When the input is raw UTF-8 bytes, decode chunks with an incremental decoder (a stateful decoder such as codecs.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 sum local_count and sort the k distinct characters by min(earliest_global_offset).

Follow-up questions

Similar questions

More Antra interview questions

All 4 Antra questions →