Number of Atoms — LeetCode 726 Python Solution

HardStackHash TableStringSorting
Problem
#726
Pattern
Stack
Reading time
2 min

The 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.

Example

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

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 726. Number of Atoms is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 726. Number of Atoms?
LeetCode 726. Number of Atoms is rated Hard on LeetCode.
What is the time complexity of LeetCode 726. Number of Atoms?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 726. Number of Atoms?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 726. Number of Atoms cover?
LeetCode 726. Number of Atoms is tagged Stack, Hash Table, String and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview