HardNo. 0726

Number of Atoms — LeetCode 726 Python Solution

Pattern
Stack
Topics
Stack, Hash Table, String, Sorting
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

Time
O(n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
1096Brace Expansion IIHard
0721Accounts MergeMedium
0720Longest Word in DictionaryMedium
0736Parse Lisp ExpressionHard
0049Group AnagramsMedium
0242Valid AnagramEasy

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.

Free to download. Check it runs on your machine, then pick a plan.