AlgoMaster Logo
AlgoMasterAnalyze GraphQL Query Costmedium

Analyze GraphQL Query Cost

medium

A GraphQL query can request nested lists whose work multiplies at every level. A server can reject an expensive query before executing it by assigning each selected field a base cost and calculating the query's total cost.

Design a GraphQLQueryCostAnalyzer class:

  • GraphQLQueryCostAnalyzer() creates a stateless analyzer.
  • int queryCost(int[][] fields) returns the total cost of the query.

Each row of fields is [parentIndex, cost, multiplier]:

  • Field 0 is the root and has parentIndex = -1.
  • Every other parent appears earlier in the array than its children.
  • A field's effective multiplier is its own multiplier multiplied by the effective multiplier of its parent.
  • A field contributes cost * effectiveMultiplier to the total.

Each call is independent. Do not reorder or mutate fields.

Example 1:

Input:

Output:

Explanation: The root contributes 1. The second field is requested 10 times and contributes 10. The final field is requested 5 times for each of those 10 parents, so it contributes 50. The total is 61.

Example 2:

Input:

Output:

Explanation: The root contributes 2. The two child fields contribute 3 * 4 = 12 and 5 * 2 = 10, so the total is 24.

Constraints

  • 1 <= fields.length <= 1000
  • fields[i].length == 3
  • fields[0][0] == -1
  • For i > 0, 0 <= fields[i][0] < i.
  • 0 <= fields[i][1] <= 10^4
  • 1 <= fields[i][2] <= 10^4
  • The answer is at most 2^31 - 1.
  • At most 100 calls are made to queryCost.
Hints

Loading...
CallReturns
new GraphQLQueryCostAnalyzer()null
queryCost([[-1,1,1],[0,1,10],[1,1,5]])61

The three effective multipliers are 1, 10, and 50, so the contributions are 1, 10, and 50.

Run checks these cases. Submit also runs a larger hidden set.