Number of Atoms
Hard
Topics
Given a chemical formula (as string s), return the count of each atom. Output the element names in alphabetical order, each followed by its count if the count is greater than 1. Groups may be nested with parentheses and followed by a multiplier.
Example 1
Input: s = "H2O" Output: "H2O"
Example 2
Input: s = "Mg(OH)2" Output: "H2MgO2"
Example 3
Input: s = "K4(ON(SO3)2)3" Output: "K4N3O21S6"
Constraints
- 1 <= s.length <= 16
- s is a valid chemical formula of element tokens, digits, and parentheses.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Parentheses nest, so the natural structure is a stack of counting maps: one map per open group. An element token adds to whichever map is on top; a closing parenthesis pops a map, scales every count by the trailing multiplier, and merges it into the map below.
The tokenising rules carry the rest. An element name is one uppercase letter followed by any number of lowercase ones — which is why the scan takes a character and then consumes lowercase greedily. A count is the digits immediately after a name or a closing parenthesis, and an absent count means 1, not 0.
Output is alphabetical with the count omitted when it is 1, so the final step is a sort over the accumulated keys.
Approach
- Keep a stack of maps, starting with one empty map for the outermost level.
- On an opening parenthesis, push a fresh map.
- On a closing parenthesis, read the trailing number (default 1), pop the top map, and merge its counts scaled by that number into the new top.
- Otherwise read an element name and its optional count, and add to the top map.
- Emit the base map's keys in sorted order, appending each count only when it exceeds 1.
Dry Run
s = "K4(ON(SO3)2)2"
token stack of maps
K4 [{K:4}]
( [{K:4}, {}]
O [{K:4}, {O:1}]
N [{K:4}, {O:1, N:1}]
( [{K:4}, {O:1, N:1}, {}]
S [{K:4}, {O:1, N:1}, {S:1}]
O3 [{K:4}, {O:1, N:1}, {S:1, O:3}]
)2 pop and scale by 2 -> {S:2, O:6}, merge
[{K:4}, {O:7, N:1, S:2}]
)2 pop and scale by 2 -> {O:14, N:2, S:4}, merge
[{K:4, O:14, N:2, S:4}]
sorted output, dropping counts of 1: K4N2O14S4
"H2O" -> H2O
"Mg(OH)2" -> H2MgO2 note Mg sorts after HComplexity
- Time — O(n log n): the scan is linear; the final sort over at most
ndistinct element names dominates. - Space — O(n) for the stack of maps, whose total size is bounded by the number of element tokens.
Common Pitfalls
- Treating an absent count as 0.
H2Ohas one oxygen, not zero, and(H2O2)with no trailing digit is multiplied by 1. - Reading an element name as a single character.
Mgis one element; splitting it intoMandgproduces plausible nonsense. - Reading only one digit of a multi-digit count.
O14is fourteen oxygens. - Multiplying the parent map instead of the popped one. The multiplier applies to the group that just closed.
- Sorting by count or by insertion order. The required order is alphabetical by element name.
- Emitting
1after an element that appears once. The format omits it. - Flattening nested groups by repeating the substring and re-parsing. It works for small inputs and is exponential in the nesting depth.
Full Solution — all languages
class Solution:
def countOfAtoms(self, s):
i = 0
n = len(s)
stack = [{}]
while i < n:
c = s[i]
if c == '(':
i += 1
stack.append({})
elif c == ')':
i += 1
start = i
while i < n and s[i].isdigit():
i += 1
mult = int(s[start:i]) if start < i else 1
top = stack.pop()
cur = stack[-1]
for key, val in top.items():
cur[key] = cur.get(key, 0) + val * mult
else:
st2 = i
i += 1
while i < n and s[i].islower():
i += 1
name = s[st2:i]
ds = i
while i < n and s[i].isdigit():
i += 1
cnt = int(s[ds:i]) if ds < i else 1
m = stack[-1]
m[name] = m.get(name, 0) + cnt
m = stack[0]
res = []
for key in sorted(m.keys()):
res.append(key)
if m[key] > 1:
res.append(str(m[key]))
return ''.join(res)import java.util.*;
class Solution {
public String countOfAtoms(String s) {
int i = 0, n = s.length();
Deque<Map<String,Long>> stack = new ArrayDeque<>();
stack.push(new HashMap<>());
while (i < n) {
char c = s.charAt(i);
if (c == '(') {
i++;
stack.push(new HashMap<>());
} else if (c == ')') {
i++;
int start = i;
while (i < n && Character.isDigit(s.charAt(i))) i++;
long mult = start < i ? Long.parseLong(s.substring(start, i)) : 1;
Map<String,Long> top = stack.pop();
Map<String,Long> cur = stack.peek();
for (Map.Entry<String,Long> e : top.entrySet()) cur.put(e.getKey(), cur.getOrDefault(e.getKey(), 0L) + e.getValue() * mult);
} else {
int st2 = i;
i++;
while (i < n && Character.isLowerCase(s.charAt(i))) i++;
String name = s.substring(st2, i);
int ds = i;
while (i < n && Character.isDigit(s.charAt(i))) i++;
long cnt = ds < i ? Long.parseLong(s.substring(ds, i)) : 1;
Map<String,Long> m = stack.peek();
m.put(name, m.getOrDefault(name, 0L) + cnt);
}
}
TreeMap<String,Long> sorted = new TreeMap<>(stack.peek());
StringBuilder sb = new StringBuilder();
for (Map.Entry<String,Long> e : sorted.entrySet()) {
sb.append(e.getKey());
if (e.getValue() > 1) sb.append(e.getValue());
}
return sb.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string countOfAtoms(string s) {
int i = 0, n = s.size();
vector<map<string,long long>> stk;
stk.push_back(map<string,long long>());
while (i < n) {
char c = s[i];
if (c == '(') {
i++;
stk.push_back(map<string,long long>());
} else if (c == ')') {
i++;
int start = i;
while (i < n && isdigit((unsigned char)s[i])) i++;
long long mult = start < i ? stoll(s.substr(start, i - start)) : 1;
map<string,long long> top = stk.back();
stk.pop_back();
for (auto& pr : top) stk.back()[pr.first] += pr.second * mult;
} else {
int st2 = i;
i++;
while (i < n && islower((unsigned char)s[i])) i++;
string name = s.substr(st2, i - st2);
int ds = i;
while (i < n && isdigit((unsigned char)s[i])) i++;
long long cnt = ds < i ? stoll(s.substr(ds, i - ds)) : 1;
stk.back()[name] += cnt;
}
}
string res = "";
for (auto& pr : stk[0]) {
res += pr.first;
if (pr.second > 1) res += to_string(pr.second);
}
return res;
}
};/**
* @param {string} s
* @return {string}
*/ var countOfAtoms = function(s) {
let i = 0;
const n = s.length;
const isDigit = (c) => c >= '0' && c <= '9';
const isLower = (c) => c >= 'a' && c <= 'z';
const stack = [ {
}
];
while (i < n) {
const c = s[i];
if (c === '(') {
i++;
stack.push({});
} else if (c === ')') {
i++;
let start = i;
while (i < n && isDigit(s[i])) i++;
const mult = start < i ? parseInt(s.substring(start, i), 10) : 1;
const top = stack.pop(), cur = stack[stack.length - 1];
for (const key in top) cur[key] = (cur[key] || 0) + top[key] * mult;
} else {
let st2 = i;
i++;
while (i < n && isLower(s[i])) i++;
const name = s.substring(st2, i);
let ds = i;
while (i < n && isDigit(s[i])) i++;
const cnt = ds < i ? parseInt(s.substring(ds, i), 10) : 1;
const m = stack[stack.length - 1];
m[name] = (m[name] || 0) + cnt;
}
}
const map = stack[0];
const keys = Object.keys(map).sort();
let res = "";
for (const key of keys) {
res += key;
if (map[key] > 1) res += map[key];
}
return res;
};