Skip to main content
All Questions

Balance a chemical equation using SymPy.

Unlock detailed company stats for this questionUpgrade

Write a Python program using SymPy that balances a chemical equation: reactants and products are separated by ' - ', compounds by ' + ', element counts follow the element symbol, no brackets. Return the integer coefficients of the balanced equation in compound order, with minimal sum.

Function: balanceEquation(chemicalEquation: str) -> list[int]. Example: 'HCl + NaOH - H2O + NaCl' -> [1, 1, 1, 1]; 'NH4ClO4 + Al - Al2O3 + HCl + H2O + N2' -> [6, 10, 5, 6, 9, 3]. Approach: parse with regex ([A-Z][a-z]?)(\d*), build the atom-balance matrix, take its nullspace, scale to minimal integers.

Format · Microsoft Data Science Intern OA (job 200041778).

Community answers

No answers contributed by the community yet.

Related courses

Course

Data Science Interview Prep

Land your dream data science role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Practice statistics, experimentation, coding, SQL, machine learning, behavioral interviews, and more.

Course

SQL Interview Prep Course

Prepare for SQL interviews with lessons on joins, aggregations, and window functions, then practice real SQL interview questions in an interactive editor with expert solutions.