call(back)
Algorithms & Data StructuresmediumSign in to star problems

Order Validator With Rule Dependencies

Build an OrderValidator that checks orders against a changing set of rules. An order is { items: [{ name, price }, ...] }.

A rule is one of:

  • { type: "prohibited", items: [names] } fails when the order contains any listed item.
  • { type: "price", min, max } fails when any item's price is below min or above max.

Operations

  • addRule(name, rule) registers a rule. Return false if the name is taken.
  • addDependency(prerequisite, rule) declares that rule is only meaningful once prerequisite has passed. Return false, changing nothing, if either name is unknown, the two are the same, the dependency already exists, or it would create a cycle.
  • removeRule(name) deletes a rule; return false if it does not exist. So that no ordering is lost, every prerequisite of the removed rule becomes a prerequisite of every rule that depended on it.
  • validate(order) evaluates the rules. A rule is skipped when any of its prerequisites failed or was skipped; otherwise it runs and passes or fails. Return { valid, failed, skipped }: failed and skipped list rule names in the order the rules were added, and valid is true when both are empty.
addRule("no-weapons", { type: "prohibited", items: ["knife"] })
addRule("price-range", { type: "price", min: 1, max: 500 })
addDependency("no-weapons", "price-range")
validate({ items: [{ name: "knife", price: 9000 }] })
  -> { valid: false, failed: ["no-weapons"], skipped: ["price-range"] }

The round is AI-assisted and grades your tests as much as the code: after implementing, write a case for each branch.

Hints

Hint 1

Store each rule once, with two sets: the rules it depends on and the rules that depend on it. Keeping both directions makes removal local.

Hint 2

A new edge prerequisite -> rule closes a cycle exactly when prerequisite is already reachable from rule. One depth-first search over dependents answers that.

Hint 3

For validate, compute each rule's status from its prerequisites' statuses with memoised recursion; the DAG guarantees it terminates.

Topics

Asked at

Similar Problems6