KatInterview

Ordered Symbol Tally by First Occurrence

StringsAuto-graded · 19 test cases
EasyAuto-gradedStringshash-mapstringcounting

Last updated

Count how often each character occurs in a string and report the tallies in the order the characters first appear, treating every character as distinct and significant.

Ordered Symbol Tally

You are given a string text. Produce a tally of how many times each distinct character occurs in it.

Rules

  • Every character counts, including spaces, digits, punctuation, and any other Unicode character. Nothing is filtered out.
  • Matching is case-sensitive: 'A' and 'a' are different characters.
  • The tally must be ordered by first occurrence: a character appears in the result at the position where it first shows up in text, not sorted alphabetically or by count.
  • Each entry in the result is a two-element list [character, count], where character is a one-character string and count is an integer. The function returns a list of these entries.
  • If text is empty, return an empty list.

Task

Implement the function so that it returns the list of [character, count] pairs described above.

Constraints

  • 0 <= len(text) <= 10^6
  • text may contain any Unicode character. Characters are the code points Python produces when iterating over the string.
  • Aim for O(n) time, where n = len(text).

Examples

Example 1

Input: ordered_symbol_tally('hello')

Output: [['h', 1], ['e', 1], ['l', 2], ['o', 1]]

Example 2

Input: ordered_symbol_tally('AaBb')

Output: [['A', 1], ['a', 1], ['B', 1], ['b', 1]]

Example 3

Input: ordered_symbol_tally('a a!')

Output: [['a', 2], [' ', 1], ['!', 1]]

Example 4

Input: ordered_symbol_tally('')

Output: []

Hints

Hint 1

You need both a count per character and a record of when each character was first seen. Think about a single structure that gives you both.

Hint 2

A Python dict remembers insertion order. If you only add a key the first time you see its character, later updates will not change its position.

Hint 3

Avoid calling `text.count(ch)` per distinct character, since that is quadratic in the worst case. Do one pass and build the output as lists, `[ch, count]`, not tuples.