AlgoMaster Logo
AlgoMasterMaintain an Incremental Materialized Viewmedium

Maintain an Incremental Materialized View

medium

A materialized view can avoid full recomputation by applying ordered changes after a durable checkpoint. The checkpoint also prevents a replayed or late event from changing an aggregate twice.

Design an IncrementalMaterializedView class:

  • IncrementalMaterializedView() creates an empty view with checkpoint 0.
  • boolean apply(int sequence, String key, int delta) accepts an event only when sequence is greater than the current checkpoint. An accepted event adds delta to key, advances the checkpoint to sequence, and returns true. Otherwise it changes nothing and returns false.
  • int value(String key) returns the current aggregate for key, or 0 when the key has not been materialized.
  • int lastApplied() returns the global checkpoint.

Sequence numbers are positive but need not be consecutive. They come from one globally ordered change stream. Receiving a larger sequence means any later event at or below that checkpoint is a duplicate or late delivery and must be ignored.

Example 1:

Input:

Output:

Explanation: Both events are newer than the checkpoint. Their deltas produce an aggregate of 8 and advance the checkpoint to 2.

Example 2:

Input:

Output:

Explanation: Sequence 5 is applied once. The duplicate 5 and late sequence 4 do not change the view.

Constraints

  • 1 <= sequence <= 10^9
  • Keys are non-empty lowercase strings.
  • -10^6 <= delta <= 10^6
  • Every aggregate fits in a signed 32-bit integer.
  • At most 10^5 method calls are made.
Hints

Loading...
CallReturns
new IncrementalMaterializedView()null
apply(1, "orders", 5)true
apply(2, "orders", 3)true
value("orders")8
lastApplied()2

Both ordered events are newer than the checkpoint. Their deltas produce an orders total of 8 and advance the checkpoint to 2.

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