✅ One Line Solution
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1.1 - One Line\nTime complexity: O(n^2).
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1.1 - One Line\nTime complexity: $$O(n^2)$$. Space complexity: $$O(n)$$.\n```python3\nclass Solution:\n    def countOfAtoms(self, s: str) -> str:\n        return [s:=re.sub(\'\\((\\w+)\\)(\\d*)\',lambda m:re.sub(\'([A-Z][a-z]*)(\\d*)\',lambda mm:mm[1]+str(int(mm[2] or 1)*int(m[2] or 1)),m[1]),s) for _ in s] and \\\n            \'\'.join(e+str(c)*(c>1) for e,c in sorted(sum((Counter({m[1]:int(m[2] or 1)}) for m in finditer(\'([A-Z][a-z]*)(\\d*)\',s)),Counter()).items()))\n```\n\n# Code #1.2 - Unwrapped\n```python3\nclass Solution:\n    def countOfAtoms(self, s: str) -> str:\n        pattern = r\'([A-Z][a-z]*)(\\d*)\'\n\n        def f(m):\n            def ff(mm):\n                return mm[1] + str(int(mm[2] or 1)*int(m[2] or 1))\n\n            return re.sub(pattern, ff, m[1])\n        \n        while \'(\' in s:\n            s = re.sub(r\'\\((\\w+)\\)(\\d*)\', f, s)\n\n        c = sum((Counter({m[1]: int(m[2] or 1)}) for m in finditer(pattern, s)), Counter())\n        \n        return \'\'.join(e + str(c)*(c>1) for e,c in sorted(c.items()))\n```\n\n# Code #2 - Regular Solution - Beats 100%\nTime complexity: $$O(n)$$. Space complexity: $$O(n)$$.\n```python3\nclass Solution:\n    def countOfAtoms(self, s: str) -> str:\n        st, i = [Counter()], 0\n        while i < len(s):\n            if s[i] == \'(\':\n                st.append(Counter())\n                i += 1\n            elif s[i] == \')\':\n                m = match(r\'(\\d*)\', s[i+1:])\n                cnt = int(m[1] or \'1\')\n                for el in st[-1]:\n                    st[-1][el] *= cnt\n                \n                cntr = st.pop()\n                st[-1] += cntr\n                i += 1 + len(m[1])\n            else:\n                m = match(r\'([A-Z][a-z]*)(\\d*)\', s[i:])\n                el, cnt = m[1], int(m[2] or \'1\')\n                st[-1][el] += cnt\n                i += len(m[0])\n        \n        return \'\'.join(el + str(cnt)*(cnt>1) for el,cnt in sorted(st[-1].items()))\n```\n---\nSee also oneliners for similar task: [1106. Parsing A Boolean Expression](https://leetcode.com/problems/parsing-a-boolean-expression/solutions/5942159/one-line-solution/)\n\n---\n(Disclaimer 2: code above is just a product of fantasy packed into one line, it is not claimed to be \'true\' oneliners - please, remind about drawbacks only if you know how to make it better)
['Hash Table', 'String', 'Sorting', 'Counting', 'Python', 'Python3']