Python | Stack | No RE | O(n)
\nfrom collections import defaultdict\n\nclass Solution:\n    def countOfAtoms(self, formula: str) -> str:\n        dt = defaultdict(int)\n        stack = [1]\n
```\nfrom collections import defaultdict\n\nclass Solution:\n    def countOfAtoms(self, formula: str) -> str:\n        dt = defaultdict(int)\n        stack = [1]\n        digits = ""\n        lowers = ""\n        for element in formula[::-1]:\n            if element.isdigit():\n                digits = element + digits\n            elif element.islower():\n                lowers = element + lowers\n            elif element == ")":\n                stack.append(stack[-1]*int(digits or 1))\n                digits = ""\n            elif element == "(":\n                stack.pop()\n            #if element is an uppercase letter\n            else:\n                element = element + lowers\n                dt[element] = dt[element]+stack[-1]*(int(digits or 1))\n                digits = ""\n                lowers = ""\n        result = []\n        for key, value in sorted(dt.items()):\n            if value == 1:\n                value = ""\n            result.append(key)\n            result.append(str(value))\n        return "".join(result)\n```
['Stack', 'Python']