> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Number of Atoms Python Solution with Tests

> Tested Python solution for LeetCode 726 with 16 pytest cases. Generate a practice environment with lcpy.

LeetCode 726, [Hard](/catalog/hard). Topics: [Hash Table](/catalog/topics/hash-table), [String](/catalog/topics/string), [Stack](/catalog/topics/stack), [Sorting](/catalog/topics/sorting). [View on LeetCode](https://leetcode.com/problems/number-of-atoms/description/).

Generate this problem as a practice environment: tested reference solution, 16 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 726   # by problem number
lcpy gen -s number_of_atoms   # by problem name
```

## Problem

Given a string `formula` representing a chemical formula, return the count of each atom.

The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.

One or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow.

* For example, `"H2O"` and `"H2O2"` are possible, but `"H1O2"` is impossible.

Two formulas are concatenated together to produce another formula.

* For example, `"H2O2He3Mg4"` is also a formula.

A formula placed in parentheses, and a count (optionally added) is also a formula.

* For example, `"(H2O2)"` and `"(H2O2)3"` are formulas.

Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.

The test cases are generated so that all the values in the output fit in a 32-bit integer.

### Examples

```
Input: formula = "H2O"
Output: "H2O"
Explanation: The count of elements are {'H': 2, 'O': 1}.
```

```
Input: formula = "Mg(OH)2"
Output: "H2MgO2"
Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
```

```
Input: formula = "K4(ON(SO3)2)2"
Output: "K4N2O14S4"
Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
```

### Constraints

* 1 \<= formula.length \<= 1000
* formula consists of English letters, digits, '(', and ')'.
* formula is always valid.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/number_of_atoms/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/number_of_atoms/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import re
from collections import Counter


class Solution:
    # Time: O(n^2) in the worst case (nested groups merged up the stack)
    # Space: O(n)
    def count_of_atoms(self, formula: str) -> str:
        stack: list[Counter[str]] = [Counter()]
        i, n = 0, len(formula)
        while i < n:
            ch = formula[i]
            if ch == "(":
                stack.append(Counter())
                i += 1
            elif ch == ")":
                i += 1
                mult_match = re.match(r"\d+", formula[i:])
                if mult_match:
                    multiplier = int(mult_match.group())
                    i += len(mult_match.group())
                else:
                    multiplier = 1
                top = stack.pop()
                for atom, count in top.items():
                    stack[-1][atom] += count * multiplier
            else:
                atom_match = re.match(r"([A-Z][a-z]*)(\d*)", formula[i:])
                if atom_match is None:
                    break
                atom = atom_match.group(1)
                count = int(atom_match.group(2)) if atom_match.group(2) else 1
                i += len(atom_match.group(0))
                stack[-1][atom] += count
        return "".join(
            atom + (str(count) if count > 1 else "") for atom, count in sorted(stack[0].items())
        )
```

## Complexity

| Time | Space |
| - | - |
| O(n^2) in the worst case (nested groups merged up the stack) | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.