Clean code || O(n + nlogn)
\n# Complexity\n- Time complexity: O(n + nlogn)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O
\n# Complexity\n- Time complexity: O(n + nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    string countOfAtoms(string s) {\n        map<string, int> mp;\n        stack<int> fact;\n        int n = s.length(), m = 1, val = 1;\n\n        for(int i = n - 1; i >= 0; i--){\n            char ch = s[i];\n            // ch --> lowercase letter\n            if(ch >= \'a\' && ch <= \'z\'){\n                string element = "";\n                while(!(s[i] >= \'A\' && s[i] <= \'Z\')){\n                    element = s[i] + element;\n                    i--;\n                }\n                element = s[i] + element;\n                int freq = m*val;\n                mp[element] += freq;\n                val = 1;\n            }\n            // ch --> uppercase letter\n            else if(s[i] >= \'A\' && s[i] <= \'Z\'){\n                string element = "";\n                element += s[i];\n                int freq = m*val;\n                mp[element] += freq;\n                val = 1;\n            }\n            else if(ch == \')\'){\n                fact.push(val);\n                m *= val;\n                val = 1;\n            }\n            else if(ch == \'(\'){\n                m /= fact.top();\n                fact.pop();\n            }\n            else{\n                string num = "";\n                while(s[i] <= \'9\' && s[i] >= \'0\'){\n                    num = s[i] + num;\n                    i--;\n                }\n                i++; \n                val = stoi(num);\n            }\n        }\n        \n        string res = "";\n        for(auto it : mp){\n            string ele = it.first;\n            string freq = "";\n            if(it.second != 1) freq += to_string(it.second);\n            res += ele + freq;\n        }\n        return res;\n    }\n};\n```
['C++']