#726

Number of Atoms

Hard
Hash TableStringStackSortingStackHash Map
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution improves efficiency by using a stack to handle nested parentheses and directly counting atoms in a single pass. This reduces the need for repeated parsing and allows for a more straightforward implementation.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a stack to manage counts and a dictionary for atom counts.
  2. 2Step 2: Loop through each character in the formula. If an uppercase letter is found, extract the full atom name and check for a following digit to determine its count.
  3. 3Step 3: If a '(' is encountered, push the current atom count dictionary onto the stack and start a new one.
  4. 4Step 4: If a ')' is encountered, pop the top dictionary from the stack and multiply its counts by any digit that follows.
  5. 5Step 5: After parsing, sort the dictionary keys and format the output string based on the counts.
solution.py33 lines
1# Full working Python code
2from collections import defaultdict
3
4def countOfAtoms(formula):
5    stack = [defaultdict(int)]
6    i = 0
7    while i < len(formula):
8        if formula[i] == '(':  # Start of a new group
9            stack.append(defaultdict(int))
10            i += 1
11        elif formula[i] == ')':  # End of a group
12            i += 1
13            multiplier = 0
14            while i < len(formula) and formula[i].isdigit():
15                multiplier = multiplier * 10 + int(formula[i])
16                i += 1
17            multiplier = multiplier or 1
18            top = stack.pop()
19            for atom, c in top.items():
20                stack[-1][atom] += c * multiplier
21        else:
22            j = i + 1
23            while j < len(formula) and formula[j].islower():
24                j += 1
25            atom = formula[i:j]
26            i = j
27            multiplier = 0
28            while i < len(formula) and formula[i].isdigit():
29                multiplier = multiplier * 10 + int(formula[i])
30                i += 1
31            multiplier = multiplier or 1
32            stack[-1][atom] += multiplier
33    return ''.join(f'{atom}{count if count > 1 else ''}' for atom, count in sorted(stack[0].items()))

Complexity note: The time complexity is O(n) because we traverse the string once, and the space complexity is O(n) due to the stack and the atom count dictionary.

  • 1Understanding how to handle nested structures (like parentheses) is crucial for parsing complex formulas.
  • 2Using a stack can greatly simplify the management of nested counts and ensure correct multiplication.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.