Python solution using recursion and regex
A given formula can either start with '(' or an atom.\ncase 1: If it starts with an atom, then we extract the starting atom and its count using regex and handle
A given formula can either start with '(' or an atom.\ncase 1: If it starts with an atom, then we extract the starting atom and its count using regex and handle the rest of the formula recursively\ncase 2: If it starts with a '(', then we find the matching ')' and use recursion twice\n         a) First we solve the sub formula inside '('  ')' using recursion and we extract the count following it and update the counts. \n        b) Then for the remainder of the formula we make a recursive call to solve it.\n```\n    def countOfAtoms(self, formula):\n        res_dict = defaultdict(int)\n        self.count_rec(formula, res_dict)\n        return ''.join(chain.from_iterable([[atom, str(res_dict[atom]) if res_dict[atom] > 1 else ''] for atom in sorted(res_dict.keys())]))\n\n    def count_rec(self, formula, res):\n        if formula is None or len(formula) == 0:\n            return\n        if formula[0] == '(':\n            count, i = 1, 1\n            while count != 0:\n                if formula[i] == '(': count += 1\n                if formula[i] == ')': count -= 1\n                i += 1\n            temp_res = defaultdict(int)\n            self.count_rec(formula[1:i-1], temp_res)\n            num = re.findall('^\\d+', formula[i:])\n            if len(num) > 0:\n                num = int(num[0])\n                i += len(str(num))\n            else:\n                num = 1\n            for atom in temp_res:\n                res[atom] += temp_res[atom] * num\n            self.count_rec(formula[i:], res)\n        else:\n            atom = re.findall('[A-Z][a-z]*', formula)[0]\n            num = re.findall('^\\d+', formula[len(atom):])\n            num = int(num[0]) if len(num) > 0 else 1\n            res[atom] += num\n            self.count_rec(formula[len(atom) + (0 if num == 1 else len(str(num))):], res)\n```
[]