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) <= 1000input_stringis 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
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"].Why fixed-step indexing fails
Stepping
2characters 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 between3("C12","C30") and2("A7","B4"). Because digit runs vary in width, we need to advance past consecutive digits dynamically.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:
- A two-index scan across
input_string:indexpoints to the current token's tag letter.digit_endstarts atindex + 1and advances whileinput_string[digit_end]is a digit. Whendigit_endstops (either on the next uppercase letter or atlen(input_string)),input_string[index + 1 : digit_end]captures the complete multi-digit integer!
- An accumulator dictionary (
totals) mapping each tag letter to its running sum inO(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_endat the end of each outer step ensures every character is visited once.- A two-index scan across
Code the segment scanner
Let's write Phase 1. Notice how
int(...)parses multi-digit slices like"250"into250and 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_endSort alphabetically and trace Example 2
Python dicts retain insertion order (first-appearance order), so
"W250K8M15W50K12"stores keys in the order'W','K','M'. Iterating oversorted(totals.keys())puts those tags into'A'-to-'Z'order before formattingf"{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 resultLet'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']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 toO(N)— Bothindexanddigit_endadvance monotonically across theNcharacters, slicing each digit run once intoint(...)(linear in digit count forN <= 1000) and updatingtotalsinO(1)average time. SortingKdistinct tag letters takesO(K log K)time, which is bounded by a tiny constant becauseK <= 26. - Space:
O(K)— Bothtotalsandresulthold at mostK <= 26entries (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_endreads"999"as999, adds1, and formats"M1000". - Zeros and leading zeros (
"B007A0B03"):int("007")evaluates to7, and'A'remains intotalswith sum0, 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
intsums 20-digit tokens accurately without overflow.
Common mistakes
- Parsing only one digit per letter (
int(input_string[index + 1])): Truncates"C12"to1and treats'2'as the next tag letter. - Advancing
index += 1instead ofindex = digit_end: Stepsindexonto digits that were already consumed, pollutingtotalswith digit keys. - Concatenating strings instead of summing ints (
"12" + "30" == "1230"): Every digit slice must be converted withint(...)before adding. - Iterating
totalswithoutsorted(...): 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 inO(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] * 26andpresent = [False] * 26indexed byord(letter) - ord('A')eliminates both hashing and sorting — simply scan0 .. 25in natural'A'-to-'Z'order and format entries wherepresent[i]isTrue.
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
whileloop: rejectlen(input_string) == 0if empty input is illegal, verify'A' <= input_string[index] <= 'Z'at the start of every token, and requiredigit_end > index + 1using'0' <= ch <= '9'rather than.isdigit()(because Python's.isdigit()accepts Unicode superscripts like'²'thatint()rejects). RaisingValueError(f"Malformed token at index {pos}")keeps validationO(N)while reporting the exact failing offset — unlikere.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_stringvisits allNcharacters once across non-overlapping slices (O(N)time), while sorting and formatting touch theKdistinct tags (O(K log K)time), givingO(N + K log K)total runtime (O(N)whenK <= 26, orO(N + K log K)if generalized to arbitrary multi-letter identifiers). Auxiliary memory isO(K)fortotalsand theK-item output list (plus up toO(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). Negatingtotalplaces the largest sums first, whileletterbreaks equal-sum ties alphabetically (for example, ordering tied totals of20as["A20", "K20"]).
Follow-up questions
- How would you validate the input if untrusted strings could include unexpected symbols, lowercase characters, or letters missing digits?
- Express the runtime and auxiliary memory in terms of the character count N and distinct tag count K.
- What changes are needed to order the returned entries from largest total to smallest instead of A-to-Z?
Similar questions
- Owning and Resolving a User-Visible Incident
- Selecting Between For and While Loops
- Navigating a Challenging Engineering Project
- JavaScript IEEE-754 Numeric Validation Utilities
- Resolving an Engineering Design Disagreement
- End-to-End Browser Lifecycle of a Web Page Load
More Riotgames interview questions
- Owning and Resolving a User-Visible Incident Easy
- Selecting Between For and While Loops Easy
- Navigating a Challenging Engineering Project Easy Pro
- JavaScript IEEE-754 Numeric Validation Utilities Easy Pro
- Resolving an Engineering Design Disagreement Easy Pro
- End-to-End Browser Lifecycle of a Web Page Load Easy Pro