AlgoMaster Logo
AlgoMasterApply Ordered CDC Changesmedium

Apply Ordered CDC Changes

medium

Change Data Capture consumers often update a search index, cache, or read model from database changes. Once events pass through partitions and parallel workers, an older change may arrive after a newer one. A consumer must prevent that late event from rolling its projection backward.

Design a CdcProjection class:

  • CdcProjection() creates an empty projection.
  • boolean apply(String key, int version, String operation, String value) applies a change when version is strictly newer than every previously accepted version for key. It returns whether the change was accepted.
  • String get(String key) returns the current value, or "" when the key is missing or deleted.

operation is either "upsert" or "delete". An upsert stores value. A delete removes the visible value but retains its version as a tombstone. Equal versions are duplicates and must be rejected. Versions belong to individual keys, not to the projection as a whole.

Example 1:

Input:

Output:

Explanation: Version 3 deletes the row and leaves a tombstone. The late version-2 upsert is rejected, so it cannot resurrect the deleted row.

Example 2:

Input:

Output:

Explanation: Key a and key b have independent version histories.

Constraints

  • 1 <= key.length <= 100
  • 0 <= version <= 10^9
  • operation is "upsert" or "delete".
  • Upsert values are non-empty and have length at most 1000; the value passed with a delete is ignored.
  • At most 10^5 total calls are made.
Hints

Loading...
CallReturns
new CdcProjection()null
apply("user:1", 1, "upsert", "active")true
get("user:1")"active"
apply("user:1", 3, "delete", "")true
get("user:1")""
apply("user:1", 2, "upsert", "stale")false
get("user:1")""

Version 3 deletes the row and leaves a tombstone. The late version-2 upsert is rejected, so the deleted row is not resurrected.

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