FastPrepChemical Formula Weight
Problem · String

Chemical Formula Weight

Learn this problem
MediumAgoda logoAgodaFULLTIMEPHONE SCREEN

Problem statement

You are given a flat chemical formula, an array of distinct element symbols elements, and a parallel array weights. The weight of elements[i] is weights[i].

Each formula term is an uppercase letter followed by zero or more lowercase letters, then an optional positive decimal count. An omitted count means 1. Terms may repeat, and the formula contains no parentheses. Every symbol in the formula appears in elements.

Return the sum of each element's weight multiplied by its count as a 64-bit integer.

Function

formulaWeight(formula: String, elements: String[], weights: int[]) → long

Examples

Example 1

formula = "CH4"elements = ["C","H"]weights = [12,1]return = 16

C contributes 12 and four H atoms contribute 4.

Example 2

formula = "H2O"elements = ["H","O"]weights = [1,2]return = 4

The supplied weights give 2 × 1 + 1 × 2 = 4.

Example 3

formula = "Na2Cl"elements = ["Na","Cl"]weights = [23,35]return = 81

The multi-letter symbols contribute 2 × 23 + 35 = 81.

Constraints

  • 1 <= formula.length <= 5000
  • 1 <= elements.length == weights.length <= 100
  • Each symbol is one uppercase letter followed by at most two lowercase letters.
  • 1 <= weights[i] <= 10^6
  • Every explicit count is between 1 and 999999.
  • The answer fits in a signed 64-bit integer.

More Agoda problems

drafts saved locally
public long formulaWeight(String formula, String[] elements, int[] weights) {
    // write your code here
}
formula"CH4"
elements["C","H"]
weights[12,1]
expected16
checking account