Parse chemical formula with multipliers
Company: TikTok
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: Parse chemical formula with multipliers evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 1 <= formula.length <= 1e5
- formula consists of English letters, digits, '(' and ')'
- formula is always a valid, balanced chemical formula
- Element subscripts and group multipliers may be multi-digit
Examples
Input: ("K4(ON(SO3)2)3",)
Expected Output: "K4N3O21S6"
Explanation: SO3 -> S1O3; (SO3)2 -> S2O6; ON(SO3)2 -> N1O7S2; group *3 -> N3O21S6; plus K4 -> K4N3O21S6 (sorted K,N,O,S).
Input: ("H2O",)
Expected Output: "H2O"
Explanation: Two hydrogen, one oxygen; oxygen's count of 1 is omitted.
Hints
- Maintain a stack of dictionaries; push a fresh counter on '(' and pop-and-merge on ')'.
- When merging a popped group, read the trailing multiplier (default 1) and scale every element count before adding it to the parent counter.
- An element symbol is one uppercase letter followed by zero or more lowercase letters; the optional digits that follow are its count (default 1).
- At the end, sort the element keys lexicographically and append the count only when it is greater than 1.