Problem 415819 · medium · Level 04 Non-Linear Data Structures

Budget Totals by Category Prefix

trie · prefix sums · classes

Design a class BudgetBook that tracks amounts per budget category and answers prefix totals:

  • put(category, amount) sets the amount for the exact string category (replacing any earlier amount).
  • total(prefix) returns the sum of the amounts of all categories that start with prefix. total("") sums everything; an unknown prefix gives 0.

Examples

ops:  ["BudgetBook", "put", "put", "total", "put", "total", "total"]
args: [[], ["food.groceries", 120], ["food.dining", 80], ["food"], ["food.groceries", 100], ["food"], ["fun"]]
Output: [None, None, None, 200, None, 180, 0]
Explanation: replacing groceries 120 -> 100 lowers the "food" total by 20.

Constraints

  • Categories and prefixes have length <= 50 (lowercase letters, digits and dots); amounts are integers, possibly negative
  • Up to 10**4 calls in total
  • Target: put and total in O(len(string)); do not scan every category per query

Goals

  • Keep an aggregate at every trie node and update it with a delta
  • Overwrite a key without double counting its old value
Starting Python…