Coding questions · TikTok
Parse chemical formula with multipliers
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.
Given a string representing a chemical formula, parse it and return the total count of each element. The formula may include element symbols (uppercase letter followed by lowercase letters), integers for counts, nested parentheses with multipliers, and multi-digit numbers. Return a canonical output by concatenating element names in lexicographic order followed by their counts (omit the count when it equals 1). For example, input "K4(ON(SO 3)2)3" should output "K4N3O14S6". Implement an algorithm that runs in O(n) time using a stack or equivalent and handles inputs up to length 1e5.
What a Strong Answer Covers
- A clear algorithm with the right data structures and enough pseudocode or code-level detail to implement it.
- A correctness argument that explains why the algorithm covers all required cases.
- Time and space complexity, plus at least one alternative approach when relevant.
- Focused tests for normal cases, edge cases, and failure modes.
Follow-up Questions
- How would the approach change if the input were streaming or too large for memory?
- What invariants would you assert in production code?
- Which tests would catch off-by-one, duplicate, or tie-breaking bugs?
Parse Chemical Formula with Multipliers
Given a string formula representing a chemical formula, parse it and return the total count of each element as a canonical string.
The formula consists of:
- Element symbols: an uppercase letter optionally followed by lowercase letters (e.g.
H,Mg,Be). - Counts: an optional integer immediately following an element or a closing parenthesis (e.g.
O2,(...)3). An absent count means 1. Counts may be multi-digit. - Groups: balanced parentheses, which may be nested, optionally followed by a multiplier that scales every element inside the group.
Return the result by concatenating each element name in lexicographic (sorted) order, followed by its total count. Omit the count when it equals 1.
Example: "K4(ON(SO3)2)3" -> "K4N3O21S6".
Solve in O(n) time using a stack of counters, supporting inputs up to length 1e5.
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
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.
Solution
Solution Alignment
The prompt asks for an implementation-level answer. The safest way to present it is to define the state, maintain clear invariants, then walk through complexity and tests.
Problem Restatement
Given a string representing a chemical formula, parse it and return the total count of each element. The formula may include element symbols (uppercase letter followed by lowercase letters), integers for counts, nested parentheses with multipliers, and multi-digit numbers. Return a canonical output by concatenating element names in lexicographic order followed by their counts (omit the count when it equals 1). For example, input "K4(ON(SO 3)2)3" should output "K4N3O14S6". Implement an algorithm that runs in O(n) time using a stack or equivalent and handles inputs up to length 1e5.
Recommended Approach
Model the states explicitly and use BFS for unweighted shortest paths, Dijkstra for weighted non-negative paths, or topological DP for DAGs. Track visited states at the right granularity so cycles do not cause repeated work.
Correctness
The implementation should maintain an invariant after each loop or operation that directly matches the problem statement. At termination, that invariant implies the returned value has considered every valid candidate exactly once, or has preserved the required data-structure state after every API call.
Complexity
BFS is O(V + E) time and O(V) space for a standard graph. Expanded-state problems multiply those bounds by the number of state dimensions.
Edge Cases and Tests
Disconnected graph, source equals target, cycles, duplicate edges, unreachable target, and whether the answer counts nodes, edges, moves, or transfers.