Python3 easy NO STACK, NO SORTING solution using eval
Intuition\nAt first glance, looks like some tedious work involving stacks. Wouldn\'t it be nice if we could delegate some of the work to the language? After all
# Intuition\nAt first glance, looks like some tedious work involving stacks. Wouldn\'t it be nice if we could delegate some of the work to the language? After all, this looks similar to what calculators do on a daily basis, isn\'t it? The (OH)2 is similar to ("OH") * 2...\n\n# Approach\nThe high level approach is as follows:\n1. Separate the code into element names and operators. Regex has been used for this conversion into tokens.\n2. Convert input like \'K4(ON(SO3)2)2\' to the equivalent like \'K * 4  + (O + N + (Se + O*3) * 2) * 2\' by looping over the tokens.\n3. Convert each of the above element tokens into a Counter object from collections. I have added support for operators, by adding the + and mul operations. This is because the regular strings can become very long, Counter object helps compress them.\n4. Generate a line of code with the elements expression and operators and let Python take care of evaluating it!\n5. Simply count the frequency of the result, sort and output.\n\n# Code\n```\nclass ExtendedCounter(Counter):\n    def __add__(self, other):\n        if isinstance(other, ExtendedCounter): return ExtendedCounter(super().__add__(other))\n    def __mul__(self, other):\n        if isinstance(other, int): return ExtendedCounter({element: count * other for element, count in self.items()})\n    \nclass Solution:\n    def countOfAtoms(self, formula: str) -> str:\n        tokens = re.findall(r\'([A-Z][a-z]?|\\d+|[()])\', formula)\n        exp = []\n        for i, token in enumerate(tokens):\n            if i > 0:\n                prev = exp[-1]\n                if token.isdigit() and prev not in \'(*\':\n                    exp.append(\'*\')\n                if (token.isalpha() or token == "(") and prev not in \'(+*\':\n                    exp.append(\'+\')\n            exp.append(f"ExtendedCounter({{\'{token}\': 1}})" if token.isalpha() else token)\n        \n        exp = \'\'.join(exp)\n        freq = defaultdict(int)\n        for element, count in eval(exp, {\'ExtendedCounter\': ExtendedCounter}).items():\n            freq[element] += count\n\n        return \'\'.join(f"{element}{count if count > 1 else \'\'}" for element, count in sorted(freq.items()))\n\n```
['Stack', 'Python3']