 9

# Number of Atoms

Difficulty: MEDIUM Contributed By
Dhruv Sharma
Avg. time to solve
50 min

Problem Statement
Suggest Edit

#### Given a formula, return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.

##### Note :
``````The given formula consists of English alphabets, digits, ‘(‘ and ’)’.

The given formula is always valid.
``````
##### Input Format
``````The first line of input contains an integer 'T' representing the number of test cases. Then the test cases follow.

The only line of each test case contains a string representing the formula.
``````
##### Output Format:
``````For each test case, return the string representing the count of all the elements is printed.

The output for each test case is in a separate line.
``````
##### Note:
``````You are not required to print the expected output, it has already been taken care of. Just implement the function.
``````
##### Constraints:
``````1 <= T <= 10
1 <= |S| <= 10^4

Time Limit: 1 sec
``````
##### Note :
``````The count of each element in the formula will not exceed 2^31.
``````
##### Sample Input 1:
``````2
H2O
Mg(OH)2
``````
##### Sample Output 1:
``````H2O
H2MgO2
``````
##### Explanation of the Sample Input 1:
``````The first formula contains two elements H and O, with their count as 2 and 1 respectively. Since the count of O is not greater than 1, it is printed as O only and H is printed as H2.

The second formula contains three elements : Mg, O and H. Mg has a count of 1 and since O and H are in parentheses followed by the digit 2, both have a count of 2.
``````
##### Sample Input 2:
``````1
K4(ON(SO3)2)2
``````
##### Sample Output 2:
``````K4N2O14S4
``````
##### Explanation of Sample Input 2
``````For the given formula, the elements are K, O, N and S. The count of K is 4, N is 2, O is 14 ( (1 + (3*2)) * 2 = 14) and that of S is 4 (2 * 2).
``````
##### Sample Input 3
``````1
Be32
``````
##### Sample Output 3
``````Be32
``````   Console