726. Number of Atoms LeetCode Solution

In this guide, you will get 726. Number of Atoms LeetCode Solution with the best time and space complexity. The solution to Number of Atoms problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Number of Atoms solution in C++
  4. Number of Atoms solution in Java
  5. Number of Atoms solution in Python
  6. Additional Resources
726. Number of Atoms LeetCode Solution image

Problem Statement of Number of Atoms

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.

See also  931. Minimum Falling Path Sum LeetCode Solution

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}.

Constraints:

1 <= formula.length <= 1000
formula consists of English letters, digits, '(', and ')'.
formula is always valid.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

726. Number of Atoms LeetCode Solution in C++

class Solution {
 public:
  string countOfAtoms(string formula) {
    string ans;
    int i = 0;

    for (const auto& [elem, freq] : parse(formula, i)) {
      ans += elem;
      if (freq > 1)
        ans += to_string(freq);
    }

    return ans;
  }

 private:
  map<string, int> parse(const string& s, int& i) {
    map<string, int> count;

    while (i < s.length())
      if (s[i] == '(') {
        for (const auto& [elem, freq] : parse(s, ++i))
          count[elem] += freq;
      } else if (s[i] == ')') {
        const int num = getNum(s, ++i);
        for (auto&& [_, freq] : count)
          freq *= num;
        return count;  // Return back to the previous scope.
      } else {         // `s[i]` must be uppercased.
        const string& elem = getElem(s, i);
        const int num = getNum(s, i);
        count[elem] += num;
      }

    return count;
  }

  string getElem(const string& s, int& i) {
    const int elemStart = i++;  // `s[elemStart]` is uppercased.
    while (i < s.length() && islower(s[i]))
      ++i;
    return s.substr(elemStart, i - elemStart);
  }

  int getNum(const string& s, int& i) {
    const int numStart = i;
    while (i < s.length() && isdigit(s[i]))
      ++i;
    const string& numString = s.substr(numStart, i - numStart);
    return numString.empty() ? 1 : stoi(numString);
  }
};
/* code provided by PROGIEZ */

726. Number of Atoms LeetCode Solution in Java

class Solution {
  public String countOfAtoms(String formula) {
    StringBuilder sb = new StringBuilder();
    Map<String, Integer> count = parse(formula);

    for (final String elem : count.keySet())
      sb.append(elem + (count.get(elem) == 1 ? "" : String.valueOf(count.get(elem))));

    return sb.toString();
  }

  private int i = 0;

  private Map<String, Integer> parse(String s) {
    Map<String, Integer> count = new TreeMap<>();

    while (i < s.length())
      if (s.charAt(i) == '(') {
        ++i; // Skip '('
        for (Map.Entry<String, Integer> entry : parse(s).entrySet()) {
          final String elem = entry.getKey();
          final int freq = entry.getValue();
          count.merge(elem, freq, Integer::sum);
        }
      } else if (s.charAt(i) == ')') {
        ++i; // Skip ')'
        final int num = getNum(s);
        for (final String elem : count.keySet()) {
          final int freq = count.get(elem);
          count.put(elem, freq * num);
        }
        return count; // Return back to the previous scope.
      } else {
        final String elem = getElem(s);
        final int num = getNum(s);
        count.merge(elem, num, Integer::sum);
      }

    return count;
  }

  private String getElem(final String s) {
    final int elemStart = i++; // `s[elemStart]` is uppercased.
    while (i < s.length() && Character.isLowerCase(s.charAt(i)))
      ++i;
    return s.substring(elemStart, i);
  }

  private int getNum(final String s) {
    final int numStart = i;
    while (i < s.length() && Character.isDigit(s.charAt(i)))
      ++i;
    final String numString = s.substring(numStart, i);
    return numString.isEmpty() ? 1 : Integer.parseInt(numString);
  }
}
// code provided by PROGIEZ

726. Number of Atoms LeetCode Solution in Python

class Solution:
  def countOfAtoms(self, formula: str) -> str:
    def parse() -> dict:
      ans = collections.defaultdict(int)

      nonlocal i
      while i < n:
        if formula[i] == '(':
          i += 1
          for elem, freq in parse().items():
            ans[elem] += freq
        elif formula[i] == ')':
          i += 1
          numStart = i
          while i < n and formula[i].isdigit():
            i += 1
          factor = int(formula[numStart:i])
          for elem, freq in ans.items():
            ans[elem] *= factor
          return ans
        elif formula[i].isupper():
          elemStart = i
          i += 1
          while i < n and formula[i].islower():
            i += 1
          elem = formula[elemStart:i]
          numStart = i
          while i < n and formula[i].isdigit():
            i += 1
          num = 1 if i == numStart else int(
              formula[numStart:i])
          ans[elem] += num

      return ans

    n = len(formula)

    ans = ""
    i = 0
    count = parse()

    for elem in sorted(count.keys()):
      ans += elem
      if count[elem] > 1:
        ans += str(count[elem])

    return ans
# code by PROGIEZ

Additional Resources

See also  868. Binary Gap LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.