726. Number of Atoms
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method Explanation
The problem requires parsing a chemical formula string, which can include nested structures via parentheses and multipliers, to count each atom. A stack-based approach is well-suited for handling the nested scopes introduced by parentheses.
Solution
Number of Atoms in Python
import collections
class Solution:
def countOfAtoms(self, formula: str) -> str:
n = len(formula)
# Stack to manage nested scopes. Each dict stores atom counts for a scope.
stack = [collections.defaultdict(int)]
i = 0
while i < n:
if formula[i] == '(':
# Start of a new nested scope
stack.append(collections.defaultdict(int))
i += 1
elif formula[i] == ')':
# End of a scope. Pop the dict, apply multiplier, and merge.
top = stack.pop()
i += 1
# Parse multiplier after ')'
start = i
while i < n and formula[i].isdigit():
i += 1
multiplier = int(formula[start:i] or 1)
# Add counts from the popped scope to the new top scope
for atom, count in top.items():
stack[-1][atom] += count * multiplier
else:
# It's an atom. Parse its name and count.
# Parse atom name (uppercase followed by optional lowercase)
start = i
i += 1
while i < n and formula[i].islower():
i += 1
atom = formula[start:i]
# Parse count
start = i
while i < n and formula[i].isdigit():
i += 1
count = int(formula[start:i] or 1)
# Add to the current scope's dict
stack[-1][atom] += count
# Final counts are in the last remaining dict on the stack.
final_counts = stack[0]
# Build the result string by sorting keys.
result = []
for atom in sorted(final_counts.keys()):
result.append(atom)
count = final_counts[atom]
if count > 1:
result.append(str(count))
return "".join(result)
Number of Atoms in Java
class Solution {
public String countOfAtoms(String formula) {
int n = formula.length();
// Stack to manage nested scopes. Each map stores atom counts for a scope.
Stack<Map<String, Integer>> stack = new Stack<>();
// Use TreeMap to keep atom names sorted alphabetically.
stack.push(new TreeMap<>());
int i = 0;
while (i < n) {
char c = formula.charAt(i);
if (c == '(') {
// Start of a new nested scope
stack.push(new TreeMap<>());
i++;
} else if (c == ')') {
// End of a scope. Pop the map, apply multiplier, and merge.
Map<String, Integer> top = stack.pop();
i++;
// Parse multiplier after ')'
int start = i;
while (i < n && Character.isDigit(formula.charAt(i))) {
i++;
}
int multiplier = start < i ? Integer.parseInt(formula.substring(start, i)) : 1;
// Add counts from the popped scope to the new top scope
for (String atom : top.keySet()) {
int count = top.get(atom);
stack.peek().put(atom, stack.peek().getOrDefault(atom, 0) + count * multiplier);
}
} else {
// It's an atom. Parse its name and count.
// Parse atom name (uppercase followed by optional lowercase)
int start = i;
i++;
while (i < n && Character.isLowerCase(formula.charAt(i))) {
i++;
}
String atom = formula.substring(start, i);
// Parse count
start = i;
while (i < n && Character.isDigit(formula.charAt(i))) {
i++;
}
int count = start < i ? Integer.parseInt(formula.substring(start, i)) : 1;
// Add to the current scope's map
stack.peek().put(atom, stack.peek().getOrDefault(atom, 0) + count);
}
}
// Final counts are in the last remaining map on the stack.
Map<String, Integer> finalCounts = stack.pop();
// Build the result string. TreeMap keys are already sorted.
StringBuilder result = new StringBuilder();
for (String atom : finalCounts.keySet()) {
result.append(atom);
int count = finalCounts.get(atom);
if (count > 1) {
result.append(count);
}
}
return result.toString();
}
}
Number of Atoms in C++
class Solution {
public:
string countOfAtoms(string formula) {
int n = formula.length();
// Stack to manage nested scopes. Each map stores atom counts for a scope.
stack<map<string, int>> s;
s.push({}); // Push an empty map for the global scope
int i = 0;
while (i < n) {
if (formula[i] == '(') {
// Start of a new nested scope
s.push({});
i++;
} else if (formula[i] == ')') {
// End of a scope. Pop the map, apply multiplier, and merge.
map<string, int> top = s.top();
s.pop();
i++;
// Parse the multiplier after ')'
int start = i;
while (i < n && isdigit(formula[i])) {
i++;
}
int multiplier = (start < i) ? stoi(formula.substr(start, i - start)) : 1;
// Add counts from the popped scope to the new top scope
for (auto const& [atom, count] : top) {
s.top()[atom] += count * multiplier;
}
} else {
// It's an atom. Parse its name and count.
// Parse atom name (uppercase followed by optional lowercase)
int start = i;
i++;
while (i < n && islower(formula[i])) {
i++;
}
string atom = formula.substr(start, i - start);
// Parse count
start = i;
while (i < n && isdigit(formula[i])) {
i++;
}
int count = (start < i) ? stoi(formula.substr(start, i - start)) : 1;
// Add to the current scope's map
s.top()[atom] += count;
}
}
// Final counts are in the last remaining map on the stack.
map<string, int> final_counts = s.top();
// Build the result string. std::map keeps keys sorted.
string result = "";
for (auto const& [atom, count] : final_counts) {
result += atom;
if (count > 1) {
result += to_string(count);
}
}
return result;
}
};
Number of Atoms in TypeScript
function countOfAtoms(formula: string): string {
const n = formula.length;
// Stack to manage nested scopes. Each map stores atom counts for a scope.
const stack: Map<string, number>[] = [new Map()];
let i = 0;
const isDigit = (char: string): boolean => char >= '0' && char <= '9';
const isLowerCase = (char: string): boolean => char >= 'a' && char <= 'z';
while (i < n) {
const char = formula[i];
if (char === '(') {
// Start of a new nested scope
stack.push(new Map());
i++;
} else if (char === ')') {
// End of a scope. Pop the map, apply multiplier, and merge.
const topMap = stack.pop()!;
i++;
// Parse multiplier after ')'
let start = i;
while (i < n && isDigit(formula[i])) {
i++;
}
const multiplier = start < i ? parseInt(formula.substring(start, i)) : 1;
// Add counts from the popped scope to the new top scope
const currentMap = stack[stack.length - 1];
for (const [atom, count] of topMap.entries()) {
currentMap.set(atom, (currentMap.get(atom) || 0) + count * multiplier);
}
} else { // It must be an uppercase letter
// It's an atom. Parse its name and count.
// Parse atom name (uppercase followed by optional lowercase)
let start = i;
i++;
while (i < n && isLowerCase(formula[i])) {
i++;
}
const atom = formula.substring(start, i);
// Parse count
start = i;
while (i < n && isDigit(formula[i])) {
i++;
}
const count = start < i ? parseInt(formula.substring(start, i)) : 1;
// Add to the current scope's map
const currentMap = stack[stack.length - 1];
currentMap.set(atom, (currentMap.get(atom) || 0) + count);
}
}
// Final counts are in the last remaining map on the stack.
const finalCounts = stack[0];
// Sort keys and build result string
const sortedAtoms = Array.from(finalCounts.keys()).sort();
let result = "";
for (const atom of sortedAtoms) {
result += atom;
const count = finalCounts.get(atom)!;
if (count > 1) {
result += count;
}
}
return result;
};
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.