Katkat

Check if CIDR is fully canceled by rules

DatabricksSoftware Engineer · Technical Screen

Last updated

This question evaluates understanding of IPv4 CIDR arithmetic, set operations on IP ranges (overlap detection and subtraction), and ordered rule semantics for allow/deny processing.

You are given:

  • A target CIDR block T as a string, e.g. "10.0.0.0/16".
  • A list of rule CIDR blocks. Each rule has:
  • A type: either "allow" or "deny".
  • A CIDR block (IPv4) as a string "a.b.c.d/x".

Interpretation of rules when applied in order to the target CIDR T:

  1. We start with the set of IPs covered by T as the "remaining" region.
  2. For each rule in the list, from first to last:
  • If the rule type is "allow" and its CIDR overlaps with the current remaining region of T, we remove ("cancel") the overlapping subset from the remaining region. (Think of this as: the allowed portion is handled elsewhere and is thus removed from what remains to be canceled.)
  • If the rule type is "deny" and its CIDR has any overlap with the current remaining region of T, we immediately return false (because a deny rule applies somewhere inside T).
  1. After processing all rules, if the remaining region of T is completely empty (i.e., all IPs in T have been canceled out by allow rules without any deny overlap), then return true. Otherwise, return false.

Task:

Implement a function that, given T and the list of (type, CIDR) rules, returns a boolean indicating whether T can be fully canceled by the rules under the above semantics.

Clarifications and requirements:

  • Use standard IPv4 and CIDR semantics; a.b.c.d/x describes all addresses sharing the first x bits with a.b.c.d.
  • Rules must be processed sequentially in the given order.
  • Overlap is defined as having at least one common IP address.
  • The remaining region of T may split into multiple disjoint CIDR ranges after applying some allow rules; you must handle such splitting correctly.
  • Target and rules are all IPv4 CIDRs; strings are syntactically valid.
  • Aim for a solution that is correct and reasonably efficient; discuss your complexity and any data structures used for representing and subtracting CIDR ranges.