Number of Atoms LeetCode Solution

Last updated on January 18th, 2025 at 03:20 am

Here, we see a Number of Atoms LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Hash Table, Recursion, Stack

Companies

Google

Level of Question

Hard

Number of Atoms LeetCode Solution

Number of Atoms LeetCode Solution

1. 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, "H2O2He3Mg4" is also a formula.

A formula placed in parentheses, and a count (optionally added) is also a formula.

  • For example, "(H2O2)" and "(H2O2)3" are formulas.

Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.

The test cases are generated so that all the values in the output fit in a 32-bit integer.

Example 1:
Input: formula = “H2O”
Output: “H2O”
Explanation: The count of elements are {‘H’: 2, ‘O’: 1}.

Example 2:
Input: formula = “Mg(OH)2”
Output: “H2MgO2”
Explanation: The count of elements are {‘H’: 2, ‘Mg’: 1, ‘O’: 2}.

Example 3:
Input: formula = “K4(ON(SO3)2)2”
Output: “K4N2O14S4”
Explanation: The count of elements are {‘K’: 4, ‘N’: 2, ‘O’: 14, ‘S’: 4}.

2. Coding Pattern Used in Solution

The coding pattern used in the provided code is “Stack-based Parsing”. The code uses stacks to handle nested structures (parentheses) and to manage multipliers for atoms in a chemical formula. This approach is common in problems involving parsing and evaluating expressions with nested or hierarchical structures.

3. Code Implementation in Different Languages

3.1 Number of Atoms C++

class Solution {
public:
    string countOfAtoms(string formula) {
        map<string, int> atoms;
        string ans;
        int cnt = 0, mult = 1;
        stack<int> st;
        
        for (int i = size(formula) - 1; i >= 0; i--) {
            if (isalpha(formula[i]) and islower(formula[i])) {
                int len = 2;
                i--;   
                while (i >= 0 and islower(formula[i])) {
                    i--;
                    len++;
                }  
                string atom = formula.substr(i, len);
                atoms[atom] += max(cnt, 1) * mult;
                cnt = 0;
            } else if (isalpha(formula[i]) and isupper(formula[i])) {
                string atom(1, formula[i]);
                atoms[atom] += max(cnt, 1) * mult;
                cnt = 0;
            } else if (isdigit(formula[i])) {
                cnt = formula[i] - '0';
                int p = 10;
                while (i - 1 >= 0 and isdigit(formula[i - 1])) {
                    cnt += p * (formula[--i] - '0');
                    p *= 10;
                }
            } else if (formula[i] == ')') {
                st.push(mult);
                mult *= max(cnt, 1);
                cnt = 0;
            } else {
                mult = st.top();
                st.pop();
            }
        }
        for (auto [atom, count]: atoms) {
            ans += atom;
            
            if (count > 1) {
                ans += to_string(count);
            }
        }
        return ans;
    }
};

3.2 Number of Atoms Java

class Solution {
    public String countOfAtoms(String formula) {
        Deque<Map<String, Integer>> stack = new ArrayDeque<>();
        Deque<Integer> numStack = new ArrayDeque<>();
        StringBuilder sb = new StringBuilder();
        StringBuilder nsb= new StringBuilder();
        stack.push(new HashMap<>());
        long num = 0;
        for (int i = formula.length()-1;i>=0;--i){
            if (formula.charAt(i)==')'){
                stack.push(new HashMap<>());
                numStack.push(getnum(nsb));
                nsb.setLength(0);
            }else if (formula.charAt(i)=='('){
                Map<String, Integer> top = stack.pop();
                int mul = numStack.pop();
                for (String key : top.keySet()){
                    stack.peek().merge(key, top.get(key)*mul, Integer::sum);
                }
            }else if (Character.isDigit(formula.charAt(i))){
                nsb.append(formula.charAt(i));
            }else if (Character.isLowerCase(formula.charAt(i))){
                sb.append(formula.charAt(i));
            }else{ // upper case
                sb.append(formula.charAt(i));
                stack.peek().merge(sb.reverse().toString(),getnum(nsb),Integer::sum);
                nsb.setLength(0);
                sb.setLength(0);
            }
        }

        Map<String, Integer> res = stack.pop();
        List<String> atoms = new ArrayList<>(res.keySet());
        Collections.sort(atoms);
        for (String key : atoms){
            sb.append(key);
            if (res.get(key)>1){
                sb.append(res.get(key));
            }
        }
        return sb.toString();
    }

    private int getnum(StringBuilder sb){
        return sb.isEmpty()?1:Integer.parseInt(sb.reverse().toString());
    }
}

3.3 Number of Atoms JavaScript

var countOfAtoms = function(formula) {
    let stack = [];
    let cur = {};
    let i = 0;
    while (i < formula.length) {
        if (formula[i] === '(') {
            stack.push(cur);
            cur = {};
            i++;
        } else if (formula[i] === ')') {
            const [mult, newI] = readNextDigit(++i);
            i = newI;
            Object.keys(cur).forEach(key => cur[key] *= mult);
            const last = stack[stack.length - 1];
            Object.keys(last).forEach(key => last[key] = last[key] + (cur[key] ?? 0));
            Object.keys(cur).forEach(key => {
               if (last[key] === undefined) {
                   last[key] = cur[key];
               } 
            });
            cur = stack.pop();
        } else {
            const [ele, newI] = readNextElement(i);
            i = newI;
            const [c, nI] = readNextDigit(i);
            i = nI;
            cur[ele] = (cur[ele] ?? 0) + c;
        }
    }
    return Object.entries(cur).sort((a,b) => a[0].localeCompare(b[0])).reduce((r, [key, val]) => r += `${key}${val === 1 ? '' : val}`, "");
    
    function readNextElement(i) {
        if (!formula[i].match(/[A-Z]/)) return null;
        let res = formula[i++];
        while (formula[i]?.match(/[a-z]/)) {
            res += formula[i++];
        }
        return [res, i];
    }
    function readNextDigit(i) {
        if (!formula[i]?.match(/[0-9]/)) return [1, i];
        let res = 0;
        while (formula[i]?.match(/[0-9]/)) {
            res = res * 10 + +formula[i++];
        }
        return [res, i];
    }
};

3.4 Number of Atoms Python

class Solution(object):
    def countOfAtoms(self, formula):
        formula = formula + ' '
        dict = {}
        m = [1]
        digit = '' 
        lower = ''
        for i in range(len(formula)-2, -1, -1):
            element = formula[i] + lower
            if element.isdigit():
                digit = element + digit
                continue
            elif element.islower():
                lower = element + lower
                continue
            elif element == ')':
                m.append(m[-1] * int(digit))
                digit = ''
                continue
            elif element == '(':
                m.pop()
                continue
            dict[element] = dict.get(element, 0) + m[-1]*int(digit or 1)
            digit = ''
            lower = ''
        output = ''
        for key, value in sorted(dict.items()):
            if value == 1:
                value = ''
            output = output + key + str(value)
        return output

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(n)O(n)
JavaO(n)O(n)
JavaScriptO(n)O(n)
PythonO(n)O(n)
Scroll to Top