🔥Cleanest & Most Concise 🔥 Stack ✅ 1 pass ✅ python3
Idea\n- Traverse from right to left to easily handle multipliers for nested parentheses.\n- Digits: Collect digits one by one, as string num\n- Letters: Build t
## Idea\n- Traverse from right to left to easily handle multipliers for nested parentheses.\n- **Digits**: Collect digits one by one, as string `num`\n- **Letters**: Build the string `element`. When an uppercase letter is encountered, the element is completed, and the`counts` dictionary is updated.\n- **Parentheses**: Update the factor and use the stack to handle nested scopes:\n    - For `)`, push the current factor onto the stack and update `multiplier`.\n    - For `(`, pop the outdated factor from the stack and divide `multiplier`, reverting to the previous multiplier. \n\n### Code with Comments\n```python\nclass Solution:\n    def countOfAtoms(self, formula: str) -> str:\n        counts = defaultdict(int)   # {element string: occurrences int}\n        stack = []                  # stores multipliers for nested parentheses\n        multiplier = 1              # actual counts for nested elements\n        num = \'\'                    # num: current number builder\n        element = \'\'                # current element builder\n\n        for i in range(len(formula) - 1, -1, -1):      # right to left\n            c = formula[i]\n            if c.isdigit():             # build the number\n                num = c + num \n            elif c.isalpha():\n                element = c + element\n                if c.isupper():         # element name completed\n                    counts[element] += multiplier * (int(num) if num else 1)\n                    element, num = \'\', \'\'\n            elif c == \')\':\n                multiplier *= int(num) if num else 1\n                stack.append(int(num) if num else 1)       \n                num = \'\'\n            else:   # \'(\'\n                multiplier //= stack.pop()      # revert to the previous multiplier\n        \n        # Construct the result string\n        result = []\n        for key in sorted(counts.keys()):\n            result.append(key)\n            if counts[key] > 1:\n                result.append(str(counts[key]))\n        return \'\'.join(result)\n```\n### Clean Version\n- @snailsmoke\'s solution in the comments simplifies even more. We can use `stack[-1]` to replace `multiplier`, update stack as we encounter `)` and `(`. \n```python\nclass Solution:\n    def countOfAtoms(self, formula: str) -> str:\n        counts = defaultdict(int)\n        stack = [1]\n        element, num = \'\', \'\'\n\n        for i in range(len(formula) - 1, -1, -1):\n            c = formula[i]\n            if c.isdigit():\n                num = c + num \n            elif c.islower():\n                element = c \n            elif c.isupper():\n                counts[c + element] += (int(num) if num else 1) * stack[-1]\n                element, num = \'\', \'\'\n            elif c == \')\':\n                stack.append((int(num) if num else 1) * stack[-1])\n                num = \'\'\n            elif c == \'(\':\n                stack.pop()\n\n        return \'\'.join(key + (str(freq) if freq > 1 else \'\') for key, freq in sorted(counts.items()))\n```
['Hash Table', 'String', 'Stack', 'Sorting', 'Python3']