Check if CIDR is fully canceled by rules
DatabricksSoftware Engineer · Technical ScreenLast 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
Tas 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:
- We start with the set of IPs covered by
Tas the "remaining" region. - 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 ofT, 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 ofT, we immediately returnfalse(because a deny rule applies somewhere insideT).
- After processing all rules, if the remaining region of
Tis completely empty (i.e., all IPs inThave been canceled out byallowrules without any deny overlap), then returntrue. Otherwise, returnfalse.
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/xdescribes all addresses sharing the firstxbits witha.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
Tmay 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.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.