Tally Tagged Numeric Segments Alphabetically

Easy · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

A compact telemetry string encodes back-to-back (tag, amount) tokens with no spaces or separators, such as "C12A7C30B4". Every token begins with one uppercase ASCII letter ('A'–'Z') immediately followed by a contiguous run of one or more base-10 digits ('0'–'9').

Implement aggregate_groups(input_string: str) -> list[str] to parse every token in input_string, sum the integer amounts attached to each distinct letter across all of its occurrences, and return a list of "<Letter><Total>" strings ordered alphabetically ('A' through 'Z').

Include only letters that appear at least once in input_string (preserving letters whose total equals 0, such as "A0").

Examples

Example 1

Input:  input_string = "C12A7C30B4"
Output: ["A7", "B4", "C42"]

Walk-through: 'C' appears twice (12 + 30 = 42), 'A' once (7), and 'B' once (4). Ordering the distinct tags from 'A' to 'Z' produces ["A7", "B4", "C42"].

Example 2

Input:  input_string = "W250K8M15W50K12"
Output: ["K20", "M15", "W300"]

Walk-through: 'W' totals 250 + 50 = 300, 'K' totals 8 + 12 = 20, and 'M' totals 15. Sorting alphabetically by tag letter gives ["K20", "M15", "W300"].

Constraints

  • 1 <= len(input_string) <= 1000
  • input_string is always well-formed: it starts with an uppercase letter 'A'–'Z', and every uppercase letter is followed by at least one digit '0'–'9'.
  • Numeric suffixes may span multiple digits (and may include '0' or leading zeros, parsed as standard base-10 integers).

Step-by-step walkthrough

  1. Restate the problem and key details

    We receive a well-formed string packed with contiguous tokens such as "C12A7C30B4". Each token begins with a single 'A'–'Z' tag letter and continues through a variable-length run of digits ('0'–'9').

    Our function must: 1. Parse every (letter, integer) token and accumulate a single integer total per distinct tag letter across the whole string. 2. Return "<Letter><Total>" strings ordered from 'A' to 'Z', such as ["A7", "B4", "C42"].

  2. Why fixed-step indexing fails

    Stepping 2 characters at a time would work only if every quantity were a single digit (like "A7B4"). Multi-digit numbers break fixed-width slicing right away:

    String:   C  1  2  A  7  C  3  0  B  4
    Index:    0  1  2  3  4  5  6  7  8  9
              |--12-|  |-7|  |--30-|  |-4|
    

    In "C12A7C30B4", token lengths alternate between 3 ("C12", "C30") and 2 ("A7", "B4"). Because digit runs vary in width, we need to advance past consecutive digits dynamically.

  3. Key idea: two indices to read segments and a dictionary to sum

    Two simple building blocks solve this cleanly in one left-to-right pass:

    1. A two-index scan across input_string:
      • index points to the current token's tag letter.
      • digit_end starts at index + 1 and advances while input_string[digit_end] is a digit. When digit_end stops (either on the next uppercase letter or at len(input_string)), input_string[index + 1 : digit_end] captures the complete multi-digit integer!
    2. An accumulator dictionary (totals) mapping each tag letter to its running sum in O(1) average time per token.
    Iteration 1 on "C12A7C30B4":
      C  1  2  A  7  C  3  0  B  4
      ^        ^
    index   digit_end   --> slice [1:3] is "12" -> int("12") = 12 -> totals['C'] = 12
                            then jump index = digit_end (3, landing right on 'A'!)
    

    Jumping index = digit_end at the end of each outer step ensures every character is visited once.

  4. Code the segment scanner

    Let's write Phase 1. Notice how int(...) parses multi-digit slices like "250" into 250 and handles leading zeros like "007" (7) automatically.

        # totals: maps uppercase letter -> integer sum of its numbers (e.g. {'A': 7, 'B': 4, 'C': 42})
        totals: Dict[str, int] = {}
        length = len(input_string)
        index = 0
    
        # Phase 1: Scan left to right, parsing one (letter, multi-digit number) segment at a time.
        while index < length:
            letter = input_string[index]
    
            # Advance digit_end across all consecutive digits so multi-digit numbers stay intact.
            digit_end = index + 1
            while digit_end < length and input_string[digit_end].isdigit():
                digit_end += 1
    
            value = int(input_string[index + 1 : digit_end])
            totals[letter] = totals.get(letter, 0) + value
    
            # Jump index directly to digit_end (the next letter, or length) so every char is visited once.
            index = digit_end
    
  5. Sort alphabetically and trace Example 2

    Python dicts retain insertion order (first-appearance order), so "W250K8M15W50K12" stores keys in the order 'W', 'K', 'M'. Iterating over sorted(totals.keys()) puts those tags into 'A'-to-'Z' order before formatting f"{letter}{totals[letter]}":

        # Phase 2: Sort distinct letters alphabetically ('A'..'Z') and format each "LetterTotal" string.
        result: List[str] = []
        for letter in sorted(totals.keys()):
            result.append(f"{letter}{totals[letter]}")
        return result
    

    Let's trace Example 2 ("W250K8M15W50K12", length = 15) end to end:

    String:     W  2  5  0  K  8  M  1  5  W  5  0  K  1  2
    Positions:  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14
    
    Step 1: index=0  ('W'), digit_end=4  -> slice [1:4]="250"  -> totals={'W': 250}
    Step 2: index=4  ('K'), digit_end=6  -> slice [5:6]="8"    -> totals={'W': 250, 'K': 8}
    Step 3: index=6  ('M'), digit_end=9  -> slice [7:9]="15"   -> totals={'W': 250, 'K': 8, 'M': 15}
    Step 4: index=9  ('W'), digit_end=12 -> slice [10:12]="50" -> totals={'W': 300, 'K': 8, 'M': 15}
    Step 5: index=12 ('K'), digit_end=15 -> slice [13:15]="12" -> totals={'W': 300, 'K': 20, 'M': 15}
    Step 6: index=15 == length -> loop ends
    
    sorted(totals.keys()) -> ['K', 'M', 'W']
    Formatted output      -> ['K20', 'M15', 'W300']
    
  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def aggregate_groups(input_string: str) -> list[str]:
        # totals: maps uppercase letter -> integer sum of its numbers (e.g. {'A': 7, 'B': 4, 'C': 42})
        totals: Dict[str, int] = {}
        length = len(input_string)
        index = 0
    
        # Phase 1: Scan left to right, parsing one (letter, multi-digit number) segment at a time.
        while index < length:
            letter = input_string[index]
    
            # Advance digit_end across all consecutive digits so multi-digit numbers stay intact.
            digit_end = index + 1
            while digit_end < length and input_string[digit_end].isdigit():
                digit_end += 1
    
            value = int(input_string[index + 1 : digit_end])
            totals[letter] = totals.get(letter, 0) + value
    
            # Jump index directly to digit_end (the next letter, or length) so every char is visited once.
            index = digit_end
    
        # Phase 2: Sort distinct letters alphabetically ('A'..'Z') and format each "LetterTotal" string.
        result: List[str] = []
        for letter in sorted(totals.keys()):
            result.append(f"{letter}{totals[letter]}")
        return result
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine tallying a compact warehouse tape printed with no spaces — "C12A7C30B4" — where each uppercase letter names an aisle and the digits right after it record a box count. To sum every aisle in a single pass, combine a two-pointer scan (two integer positions advancing left to right so no character is inspected twice) with a hash map (a Python dict storing key-value pairs with O(1) average lookup and update time): stand index on the aisle letter, march digit_end across all consecutive digits following it to capture the complete multi-digit count, add int(...) to totals[letter], and jump index directly to digit_end. Once the scan reaches the end, sort the distinct letters in lexicographical order (standard 'A'-to-'Z' alphabetical order) and format each "<Letter><Total>" string.

Why do naive shortcuts break? Stepping two characters at a time splits multi-digit numbers like "C12" into "C1" plus a stray '2', while concatenating digit substrings instead of calling int() turns "C12" and "C30" into "C1230" rather than "C42". Emitting dictionary keys without sorting also fails whenever tags first appear out of alphabetical order, as in "C12A7".

Let's trace Example 2 ("W250K8M15W50K12") step by step:

1. index=0  ('W'), digit_end=4  -> int("250") = 250 -> totals = {'W': 250}
2. index=4  ('K'), digit_end=6  -> int("8")   = 8   -> totals = {'W': 250, 'K': 8}
3. index=6  ('M'), digit_end=9  -> int("15")  = 15  -> totals = {'W': 250, 'K': 8, 'M': 15}
4. index=9  ('W'), digit_end=12 -> int("50")  = 50  -> totals = {'W': 300, 'K': 8, 'M': 15}
5. index=12 ('K'), digit_end=15 -> int("12")  = 12  -> totals = {'W': 300, 'K': 20, 'M': 15}
6. Sort keys ['K', 'M', 'W'] -> ["K20", "M15", "W300"]

Complexity

Let N be len(input_string) and K be the number of distinct uppercase letters present (K <= 26).

  • Time: O(N + K log K), which simplifies to O(N) — Both index and digit_end advance monotonically across the N characters, slicing each digit run once into int(...) (linear in digit count for N <= 1000) and updating totals in O(1) average time. Sorting K distinct tag letters takes O(K log K) time, which is bounded by a tiny constant because K <= 26.
  • Space: O(K) — Both totals and result hold at most K <= 26 entries (O(1) auxiliary space relative to the fixed uppercase alphabet).

Edge cases

  • Single token ("Q7"): Outer loop runs once and returns ["Q7"].
  • Repeated tag adjacent or separated ("A1A2A3" or "C12A7C30B4"): Both accumulate cleanly into the same dictionary slot.
  • Multi-digit carries ("M999M1"): digit_end reads "999" as 999, adds 1, and formats "M1000".
  • Zeros and leading zeros ("B007A0B03"): int("007") evaluates to 7, and 'A' remains in totals with sum 0, returning ["A0", "B10"].
  • Out-of-order first appearance ("D4C3B2A1"): sorted(totals.keys()) reorders the keys to ["A1", "B2", "C3", "D4"].
  • Quantities exceeding 64-bit integers: Python's arbitrary-precision int sums 20-digit tokens accurately without overflow.

Common mistakes

  • Parsing only one digit per letter (int(input_string[index + 1])): Truncates "C12" to 1 and treats '2' as the next tag letter.
  • Advancing index += 1 instead of index = digit_end: Steps index onto digits that were already consumed, polluting totals with digit keys.
  • Concatenating strings instead of summing ints ("12" + "30" == "1230"): Every digit slice must be converted with int(...) before adding.
  • Iterating totals without sorted(...): Preserves first-seen order (["C42", "A7", "B4"]) instead of alphabetical order (["A7", "B4", "C42"]).
  • Filtering out zero totals (if totals[letter]:): Drops valid "A0" entries when a letter only appeared with zero values.

Alternative approaches

  • Regular expression extraction: A regular expression (a declarative pattern for matching character sequences), such as re.findall(r"([A-Z])([0-9]+)", input_string), pulls out all (letter, digits) pairs in O(N) time. The explicit two-index scan avoids regex engine overhead and pinpoints exact character offsets whenever input validation is added.
  • 26-slot fixed array: Keeping sums = [0] * 26 and present = [False] * 26 indexed by ord(letter) - ord('A') eliminates both hashing and sorting — simply scan 0 .. 25 in natural 'A'-to-'Z' order and format entries where present[i] is True.

Follow-up questions

  • How would you validate the input if untrusted strings could include unexpected symbols, lowercase characters, or letters missing digits? Clarify upfront whether invalid tokens should raise an exception immediately or be logged and skipped, then guard three invariants inside the while loop: reject len(input_string) == 0 if empty input is illegal, verify 'A' <= input_string[index] <= 'Z' at the start of every token, and require digit_end > index + 1 using '0' <= ch <= '9' rather than .isdigit() (because Python's .isdigit() accepts Unicode superscripts like '²' that int() rejects). Raising ValueError(f"Malformed token at index {pos}") keeps validation O(N) while reporting the exact failing offset — unlike re.findall, which silently ignores stray characters between matches.
  • Express the runtime and auxiliary memory in terms of the character count N and distinct tag count K. Scanning input_string visits all N characters once across non-overlapping slices (O(N) time), while sorting and formatting touch the K distinct tags (O(K log K) time), giving O(N + K log K) total runtime (O(N) when K <= 26, or O(N + K log K) if generalized to arbitrary multi-letter identifiers). Auxiliary memory is O(K) for totals and the K-item output list (plus up to O(N) transient slice storage if a single giant number spans almost the entire string).
  • What changes are needed to order the returned entries from largest total to smallest instead of A-to-Z? Leave Phase 1 unchanged and sort totals.items() with a small helper key function returning (-total, letter). Negating total places the largest sums first, while letter breaks equal-sum ties alphabetically (for example, ordering tied totals of 20 as ["A20", "K20"]).

Follow-up questions

Similar questions

More Riotgames interview questions

All 7 Riotgames questions →