Practice › Strings
Number of Atoms
Hard · Strings · Asked at Google, Amazon, Microsoft
A chemical formula has atoms (an uppercase letter followed by zero or more lowercase letters), optional counts after atoms or after closing brackets, and nested parentheses — for example K4(ON(SO3)2)2. A missing count means 1. Print the total count of every atom: atom names in alphabetical order, each followed by its count, and the count omitted when it is 1.
Input
A single line with the formula (always valid).
Output
The atom counts, e.g. K4N2O14S4.
Constraints
- 1 ≤ length ≤ 1000
- every count fits in a 32-bit signed integer
Use a stack of maps. "(" pushes a new empty map; ")" pops it, multiplies every count by the number that follows, and merges it into the map below. Atoms add their count to the top map.
Example 1
Input
H2O
Output
H2O
Example 2
Input
Mg(OH)2
Output
H2MgO2
Example 3
Input
K4(ON(SO3)2)2
Output
K4N2O14S4
Hints
- Parentheses nest, so a stack is natural: one count table per open bracket.
- An atom name is one uppercase letter followed by any lowercase letters; a missing number means 1.
- At ")", read the multiplier and merge the popped table, multiplied, into the one below.
Approach
Scan the formula with an index. "(" pushes an empty map. An atom name is read, then its count (default 1), and added to the top map. ")" pops the top map, reads the multiplier (default 1) and adds every count × multiplier into the new top. At the end, sort the atoms of the single remaining map alphabetically and print name + count (count omitted when it is 1). A sorted map (std::map / TreeMap) keeps the order for free.
Complexity: O(n · depth + k log k) time · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
string f;
size_t i = 0;
long long readNum() {
if (i >= f.size() || !isdigit(f[i])) return 1;
long long v = 0;
while (i < f.size() && isdigit(f[i])) v = v * 10 + (f[i++] - '0');
return v;
}
int main() {
cin >> f;
vector<map<string, long long>> st(1);
while (i < f.size()) {
if (f[i] == '(') {
st.emplace_back();
i++;
} else if (f[i] == ')') {
i++;
long long k = readNum();
map<string, long long> top = st.back();
st.pop_back();
for (auto &p : top) st.back()[p.first] += p.second * k;
} else {
string name(1, f[i++]);
while (i < f.size() && islower(f[i])) name += f[i++];
st.back()[name] += readNum();
}
}
string out;
for (auto &p : st[0]) out += p.first + (p.second > 1 ? to_string(p.second) : "");
cout << out << "\n";
return 0;
}Python solution
from collections import defaultdict
f = input().strip()
i, n = 0, len(f)
def read_num():
global i
j = i
while i < n and f[i].isdigit():
i += 1
return int(f[j:i]) if i > j else 1
stack = [defaultdict(int)]
while i < n:
c = f[i]
if c == "(":
stack.append(defaultdict(int))
i += 1
elif c == ")":
i += 1
k = read_num()
top = stack.pop()
for atom, v in top.items():
stack[-1][atom] += v * k
else:
j = i
i += 1
while i < n and f[i].islower():
i += 1
name = f[j:i]
stack[-1][name] += read_num()
print("".join(a + (str(v) if v > 1 else "") for a, v in sorted(stack[0].items())))Java solution
import java.io.*;
import java.util.*;
public class Main {
static String f;
static int i = 0;
static long readNum() {
if (i >= f.length() || !Character.isDigit(f.charAt(i))) return 1;
long v = 0;
while (i < f.length() && Character.isDigit(f.charAt(i))) v = v * 10 + (f.charAt(i++) - '0');
return v;
}
public static void main(String[] args) throws IOException {
f = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
ArrayDeque<TreeMap<String, Long>> st = new ArrayDeque<>();
st.push(new TreeMap<>());
while (i < f.length()) {
char c = f.charAt(i);
if (c == '(') {
st.push(new TreeMap<>());
i++;
} else if (c == ')') {
i++;
long k = readNum();
TreeMap<String, Long> top = st.pop();
for (Map.Entry<String, Long> e : top.entrySet()) st.peek().merge(e.getKey(), e.getValue() * k, Long::sum);
} else {
int j = i++;
while (i < f.length() && Character.isLowerCase(f.charAt(i))) i++;
String name = f.substring(j, i);
st.peek().merge(name, readNum(), Long::sum);
}
}
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, Long> e : st.peek().entrySet()) {
sb.append(e.getKey());
if (e.getValue() > 1) sb.append(e.getValue());
}
System.out.println(sb);
}
}