Advertisement

Number of Atoms - LeetCode 726 Solution

Number of Atoms - Complete Solution Guide

Number of Atoms is LeetCode problem 726, a Hard level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

Given a string formula representing a chemical formula, return the count of each atom . The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name. One or more digits representing that element's count may follow if the count is greater than 1 . If the count is 1 , no digits will follow. For example, "H2O" and "H2O2" are possible, but "H1O2" is impossible. Two formulas are concatenated together to produce another formula. For example,

Detailed Explanation

The problem asks us to take a chemical formula string as input and return a string representing the count of each atom in the formula, sorted alphabetically. The formula can contain atomic elements (starting with an uppercase letter), numbers representing counts, parentheses for grouping, and concatenation of formulas. The output should be formatted as the element name followed by its count if the count is greater than 1, all concatenated together. For example, 'H2O' should return 'H2O', and 'Mg(OH)2' should return 'H2MgO2'. The input string is guaranteed to be a valid formula and the counts fit within a 32-bit integer.

Solution Approach

The provided code uses a stack-based approach to parse the chemical formula. It iterates through the string, maintaining a stack of hash maps (or dictionaries). Each hash map on the stack represents the atom counts at a particular level of nesting within parentheses. When an opening parenthesis is encountered, a new hash map is pushed onto the stack. When a closing parenthesis is encountered, the hash map on the top of the stack is popped, and its counts are multiplied by the number following the parenthesis (if any) and added to the counts in the hash map below it. Atomic elements and their counts are parsed and added to the hash map at the top of the stack. Finally, the atom counts in the bottom hash map are sorted alphabetically, and the result string is constructed.

Step-by-Step Algorithm

  1. Step 1: Initialize an empty stack to store hash maps (atom counts) and push an empty hash map onto the stack.
  2. Step 2: Iterate through the formula string character by character.
  3. Step 3: If the current character is '(', push a new empty hash map onto the stack and increment the index.
  4. Step 4: If the current character is ')', pop the top hash map from the stack. Parse the number following the closing parenthesis (if any) as the multiplier. Iterate through the elements in the popped hash map, multiplying each count by the multiplier and adding it to the corresponding element in the hash map at the top of the stack. Increment the index appropriately.
  5. Step 5: If the current character is an uppercase letter, parse the element name (potentially including lowercase letters) and its count (if any). Add the element and its count to the hash map at the top of the stack. Increment the index appropriately.
  6. Step 6: After processing the entire string, retrieve the final atom counts from the hash map at the bottom of the stack.
  7. Step 7: Sort the elements alphabetically.
  8. Step 8: Build the result string by iterating through the sorted elements and appending the element name and its count (if greater than 1) to the string.
  9. Step 9: Return the result string.

Key Insights

  • Insight 1: The use of a stack is crucial for handling the nested parentheses and correctly applying multipliers to the atom counts within each group.
  • Insight 2: A hash map (or dictionary) is essential to efficiently store and update the counts of each atom as the formula is parsed.
  • Insight 3: The final result needs to be sorted alphabetically by element name, implying the use of sorting or a data structure that maintains sorted order (like TreeMap in Java).
  • Insight 4: Parsing digits from the string needs careful handling to avoid errors when multipliers or atom counts are implicitly '1'.

Complexity Analysis

Time Complexity: O(n^2)

Space Complexity: O(n)

Topics

This problem involves: Hash Table, String, Stack, Sorting.

Companies

Asked at: Confluent, Coupang, Docusign, Fastenal.