Number of Atoms

Hard

Topics
Hash TableStringStackSorting

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

H021O2
Input:  s = "H2O"
Output: "H2O"

Example 2

M0g1(2O3H4)526
Input:  s = "Mg(OH)2"
Output: "H2MgO2"

Example 3

K041(2O3N4(5S6O738)9210)11312
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

  1. Keep a stack of maps, starting with one empty map for the outermost level.
  2. On an opening parenthesis, push a fresh map.
  3. 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.
  4. Otherwise read an element name and its optional count, and add to the top map.
  5. 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 H

Complexity

  • Time — O(n log n): the scan is linear; the final sort over at most n distinct 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. H2O has one oxygen, not zero, and (H2O2) with no trailing digit is multiplied by 1.
  • Reading an element name as a single character. Mg is one element; splitting it into M and g produces plausible nonsense.
  • Reading only one digit of a multi-digit count. O14 is 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 1 after 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)
SensAI
Beta
Tap the mic to stop voice mode