Balance a Chemical Equation
Updated
Problem statement
Given an unbalanced chemical equation, return the smallest positive integer coefficient for every compound in the order the compounds appear.
Reactants and products are separated by " - ", and compounds on either side are separated by " + ". An element symbol starts with an uppercase letter and may have one lowercase letter. Its following decimal count defaults to 1; an element may appear more than once in one formula. Inputs contain no brackets, charges, hydrates, or isotopes.
The returned coefficients must make every element's total atom count equal on both sides. Divide the coefficients by their greatest common divisor so their sum is minimal.
Function
balanceEquation(chemicalEquation: String) → int[]Examples
Example 1
chemicalEquation = "HCl + NaOH - H2O + NaCl"return = [1,1,1,1]Each element already has equal totals on both sides.
Example 2
chemicalEquation = "NH4ClO4 + Al - Al2O3 + HCl + H2O + N2"return = [6,10,5,6,9,3]These are the smallest positive integers that balance nitrogen, hydrogen, chlorine, oxygen, and aluminum.
Constraints
- The equation contains between
2and7compounds total, with at least one on each side. - Every atom count is between
1and50. - The equation has a unique one-dimensional balance whose coefficients are all positive.
- Every normalized coefficient is at most
10^9.
Source note: The source image is a source-neutral excerpt of the author-reported prompt.
More Microsoft Online Assessment questions
- Authentication SystemOA · Seen Nov 2026
- Maximum String OperationsOA · Seen Nov 2026
- Minimum Cost to Process Priority TasksOA · Seen Nov 2026
- Most Visited Sprint MarkerOA · Seen Nov 2026
- Maximum Escape Game ScoreOA · Seen Nov 2026
- Count Subarrays with a Perfect-Square ProductOA · Seen Nov 2026
- Maximum Interactive Team SizeOA · Seen Nov 2026
- Maximize Pipeline Throughput Under a Scaling BudgetOA · Seen Nov 2026
- Minimum Cost K-Capable ModelsOA · Seen Nov 2026
- Find Available Meeting RoomsOA · Seen Oct 2026
Similar questions at other companies
- Smallest Value for a Linear Expression ModuloIntel · OA
- Polynomial CoefficientsShopify · OAShopify interview questions
- Simplify a Quadratic ExpressionOpenAI · OAOpenAI interview questions
- Is This Date a Weekend?Salesforce · OASalesforce interview questions
- Flip Rows and Columns, Count ZerosNutanix · OANutanix interview questions
- Hidden ArtifactsIMC Trading · OAIMC Trading interview questions
- Parse, Normalize, and Combine PolynomialsSquarepoint Capital · PHONE SCREENSquarepoint Capital interview questions
- Transaction Fee Calculator — Parts 1–2: Basic Fee Calculation and Conditional Fee RulesStripe · PHONE SCREENStripe interview questions
- Evaluate an Arithmetic Expression Written in WordsBrex · PHONE SCREEN
- Stack Formula InterpreterTypeSafe AI · PHONE SCREEN