Map Sum Pairs

MediumDesigntrie

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Implement MapSum, a string-to-integer map that can total values by key prefix. - MapSum() creates an empty map. - insert(key, val) sets key to val. If key already exists, its old value is **replaced**, not added to. - sum(prefix) returns the sum of the values of all keys that start with prefix (a key counts as starting with itself). If no key matches, return 0.

Examples

Input: ["MapSum","insert","sum","insert","sum"] [[],["apple",3],["ap"],["app",2],["ap"]]
Output: [null,null,3,null,5]
Only "apple" starts with "ap" at first (3). After adding "app" with 2, both keys match: 3 + 2 = 5.
Input: ["MapSum","insert","insert","sum","insert","sum","sum","sum"] [[],["car",4],["cat",1],["ca"],["car",10],["car"],["ca"],["dog"]]
Output: [null,null,null,5,null,10,11,0]
Re-inserting "car" overwrites 4 with 10, so "car" sums to 10 and "ca" to 10 + 1 = 11. No key starts with "dog".

Constraints

  • 1 <= key.length, prefix.length <= 50
  • `key` and `prefix` consist of lowercase English letters
  • 1 <= val <= 1000
  • At most 50 calls to `insert` and `sum`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More trie problems