Python Solution; Core logic O(N); beats 95%; with explanation and inline comments
\nIntuition: This problem is testing you basic compiler algorithms, however you don\'t have to understand compiler if you can solve similar parentheses problem 
\nIntuition: This problem is testing you basic compiler algorithms, however you don\'t have to understand compiler if you can solve similar parentheses problem family on Leetcode.\nKey point:\n    1. Scan the characters backward.\n    2. Use stack, just simple stack. Not the complicated one used in the official solution.\n    3. You also need a dict/hash/map/Counter.\nRunning Time: Total O(N log N) due to sorting; However, other than that the core code is **O(N)**.\nSpace: O(N) for the stack and counter\n```\nclass Solution: \n    def countOfAtoms(self, formula):\n        counter = collections.Counter()\n        N = len(formula)\n        \n        count = 1 # The most recent integer encountered\n        stack = [] # Keep track of all the counts pushed in\n        weight = 1 # common weight; equals to the product of multiplying all the counts in current stack\n        \n        i = N-1\n        \n        while i >= 0:\n            low = \'\' # by default, assume no lower case\n            count = 1 # by default, no count specified means count=1\n            # Deal with digit\n            if formula[i].isdigit(): # always try calculate count first so it can be used by the rest of code\n                j = i\n                while i>=0 and formula[i].isdigit(): i-=1 # could test if i>=0 after this point, however the problem guarantees an upper case letter on the left\n                count = int(formula[i+1:j+1])\n            \n            # Deal with )\n            if formula[i] == \')\':\n                weight *= count\n                stack.append(count)\n            # Deal with (\n            elif formula[i] == \'(\':\n                weight //= stack.pop()\n            # Deal with elements\n            elif formula[i].islower():\n                low = formula[i]\n                i-=1 # could test if i>=0 after this point, however the problem guarantees an upper case letter on the left\n            \n            if formula[i].isupper(): # always try handle upper case at last, so it has all the information\n                e = formula[i]+low\n                counter[e]+=count*weight\n            i-=1\n        ans = []\n        for e in sorted(counter.keys()):\n            ans.append(e)\n            if counter[e]>1: ans.append(str(counter[e]))\n        return \'\'.join(ans)\n```
[]