Problem 411841 · hard · Phase 04 Non-Linear Data Structures

Price Ledger With Range Counts

binary search tree · augmented tree · class design · order statistics

Implement a class RangeLedger that records prices and answers range questions, backed by your own search tree:

  • RangeLedger() starts empty;
  • add(x) records one more price x (repeats allowed);
  • count(lo, hi) returns how many recorded prices p satisfy lo <= p <= hi.

Tests use run_ops; the result list has None for the constructor and for add.

Examples

After adding 10, 4, 17, 8 in that order the tree looks like:

    10
   /  \
  4    17
   \
    8                level order [10, 4, 17, None, 8]

ops  = ["RangeLedger", "add", "add", "add", "add", "count", "count", "add", "count"]
args = [[], [10], [4], [17], [8], [5, 12], [0, 3], [4], [4, 4]]
Output: [None, None, None, None, None, 2, 0, None, 2]

Constraints

  • Up to 3000 operations; prices are integers
  • lo <= hi in every query
  • Aim for O(h) per operation by keeping, in every node, the number of prices stored in its subtree

Goals

  • Store subtree sizes so counts need no full traversal
  • Answer 'how many values are at most x' along one search path
  • Support repeated values with a per-node counter
Starting Python…