TikTok/ByteDance Phone Interview Question
Anonymous User
4767

Got a weird question during my phone screen with TikTok after passing their OA, got the base cases working but ran out of time before getting all edge cases down. Overall not a hard problem imo, just rather tedious and lots of edge cases when dealing with pointers. I was attempting to do it all in 1 pass of the string, is there anything I'm missing? As is, seems rather tricky to accomplish in just 40 mins of coding.

Given a chemical formula composed of  chemical element symbols, numbers, and parentheses, compute the total count of each atom.

Input:
1) An atomic element starts with an uppercase character, followed by zero or more lowercase letters.
2) One or more digits representing the count of that element may follow if the count is greater than 1. Example: H2O and H2O2 are valid, but H2O1 is not valid.
3) Formulas concatenated together produce another formula. Example, H2O2He3Mg4.
4) A formula placed in parentheses followed by a count (optionally added) is also a formula. Example, (H2O2) and (H2O2)3 are correct formulas.

Output:
An unsorted map whose keys are the atoms in the input chemical formula and the values are the total counts of that respective atom.

Example 1:
Input: "H2O"
Output: {"H": 2, "O": 1}

Example 2:
Input: "K4(OMg(SO3)2)2"
Output: {'K': 4, 'Mg': 2, 'O': 14, 'S': 4}.
Comments (3)