Revision 02c131e7-26c3-4710-a331-2a9de4bc8c37 - Code Golf Stack Exchange
#Python (<strike>312</strike> 309 chars)
import re
a,d,o,e=[],{},"",len(i)-1
for b in i:a.append(dict(re.findall(r"([A-Z][a-z]*)(\d*)",b)))
a=[{b:int(c[b])if c[b]else 1for b in c}for c in a]
for b in a:
for c in b:d[c]=d[c]+b[c]if c in d else b[c]
if"H"not in b:d["-"]=0
d["H"]-=2*e
d["O"]-=e
for b in d:o+=b+(str(d[b])if d[b]-1else"")if d[b]else""
The input for this piece of code is the array of strings `i`, and the output is `o`. Here is an example of the code with input, output, and comments added in:
import re
i=["HgHO4","C6H12O6"] #input, as an array of strings
a,d,o,e=[],{},"",len(i)-1 #vars b and c are used for iterating, and are not defined here
for b in i:a.append(dict(re.findall(r"([A-Z][a-z]*)(\d*)",b))) #convert each molecule from string to a dictionary and store into a
a=[{b:int(c[b])if c[b]else 1for b in c}for c in a] #convert all "subscripts" in a to ints, making empty strings into 1s
for b in a:
for c in b:d[c]=d[c]+b[c]if c in d else b[c] #add key/value pairs of array of dictionaries a to dictionary d
if"H"not in b:d["-"]=0 #check that all molecules have at least one H(ydrogen)
d["H"]-=2*e #remove H(ydrogen)
d["O"]-=e #remove O(xygen)
for b in d:o+=b+(str(d[b])if d[b]-1else"")if d[b]else"" #convert dictionary d into output string o
print(o) #print output