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.
Input: ("Mg(OH)2",)
Expected Output: "H2MgO2"
Explanation: (OH)2 -> O2H2; plus Mg1; sorted lexicographically: H2, Mg, O2.
Input: ("H",)
Expected Output: "H"
Explanation: Single element with implicit count 1, so no number is appended.
Input: ("(H2O2)10",)
Expected Output: "H20O20"
Explanation: Group multiplier scales both H2 and O2 by 10.
Input: ("Be32",)
Expected Output: "Be32"
Explanation: Two-letter element symbol with a multi-digit subscript.
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.