FastPrepBalance a Chemical Equation

Balance a Chemical Equation

Microsoft logoMicrosoft● HardINTERNOA
Learn

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 2 and 7 compounds total, with at least one on each side.
  • Every atom count is between 1 and 50.
  • 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 problems

See Microsoft hiring insights
public int[] balanceEquation(String chemicalEquation) {
  // Write your code here.
}
chemicalEquation"HCl + NaOH - H2O + NaCl"
expected[1,1,1,1]
Checking account…