Molecular Weight of a Grouped Formula
Updated
Problem statement
Given a valid molecular formula containing only C, H, O, parentheses, and optional single-digit multipliers, return its molecular weight.
Carbon has weight 12, hydrogen has weight 1, and oxygen has weight 8. A multiplier applies to the immediately preceding atom or parenthesized group. Parentheses may be nested.
Function
molecularWeight(formula: String) → intExamples
Example 1
formula = "H(CH4)2"return = 33The leading hydrogen weighs 1, while each grouped CH4 weighs 16 and occurs twice.
Example 2
formula = "C(OH)3"return = 39Carbon contributes 12 and each of the three OH groups contributes 9.
Constraints
1 <= formula.length <= 100.- The formula is valid and contains only
C,H,O, parentheses, and digits2through9. - Every computed weight fits a signed 32-bit integer.
More Agoda interview questions
- Sort Ones, Twos, and Threes In PlacePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Minimum Daily Printing LimitONSITE INTERVIEW · Seen Aug 2026
- Climb Stairs with One, Two, or Three StepsONSITE INTERVIEW · Seen Aug 2026
- Rank Transform an ArrayONSITE INTERVIEW · Seen Aug 2026
- Minimum Absolute Difference PairsONSITE INTERVIEW · Seen Jun 2026
- Feasibility of Printing Within Given DaysONSITE INTERVIEW · Seen May 2026
- 3SumONSITE INTERVIEW · Seen May 2026
- Can Place FlowersPHONE SCREEN · Seen Nov 2026
- Reverse Words in a StringPHONE SCREEN · Seen Nov 2026
- Disk Space Window AnalyzerPHONE SCREEN · Seen Sep 2026
Similar questions at other companies
- Most Frequent Call Path From Function Trace LogsRoblox · PHONE SCREEN · ONSITE INTERVIEWRoblox interview questions
- Single-Pass S-Expression ParserBaseten · ONSITE INTERVIEWBaseten interview questions
- Flatten a Mixed JSON ListNike, Inc. · ONSITE INTERVIEWNike, Inc. interview questions
- Calculate a Token-List ExpressionCollege Vine · ONSITE INTERVIEW
- Rich Text Parser Part 3 (Depth Tokens)Figma · PHONE SCREEN · ONSITE INTERVIEWFigma interview questions
- Parse Nested HTML into a TreeApple · ONSITE INTERVIEWApple interview questions
- Calculator with ParenthesesGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Lisp Expression ParserAmazon · ONSITE INTERVIEW
- Lisp Expression ParserAttentive · ONSITE INTERVIEWAttentive interview questions
- Flatten Nested Map Paths with a StackSalesforce · ONSITE INTERVIEWSalesforce interview questions