Sequential Allow/Deny Rules Over an IPv4 Block
Greedy & IntervalsAuto-graded · 23 test casesLast updated
Track an IPv4 block as disjoint integer intervals while applying ordered allow and deny CIDR rules, deciding whether the block ends up fully covered with no deny hit.
Clearing an IPv4 Block with Ordered Rules
You are given a target IPv4 block written in CIDR notation, plus an ordered list of rules. Each rule is a pair [kind, cidr], where kind is either "allow" or "deny" and cidr is an IPv4 block such as "a.b.c.d/x".
A CIDR block a.b.c.d/x stands for every address that shares its first x bits with a.b.c.d.
Process
Begin with an uncleared region equal to the set of all addresses in the target block. Then handle the rules one at a time, from first to last:
allowrule: every address of the uncleared region that also lies in the rule's block is removed from the region. Addresses outside the region are unaffected.denyrule: if the rule's block shares at least one address with the uncleared region as it is at that moment, the process stops immediately and the answer isfalse.
When every rule has been handled, the answer is true if the uncleared region is empty, and false otherwise.
Task
Implement the function that, given the target block and the rule list, returns true if the target is completely cleared under the process above, and false otherwise.
Notes
- Rules must be applied strictly in the given order. A deny rule is tested only against what remains uncleared at its turn, not against the original target.
- Removing part of the region from its middle can leave several separate pieces; these must all be tracked correctly.
- All strings are valid IPv4 CIDR notation. The address part may have host bits set (for example
10.0.0.7/24); such a block means the same as its network form (10.0.0.0/24). - Any rule kind other than
"deny"can be treated as"allow". - With an empty rule list the target is never cleared, so the result is
false.
Constraints
- The target and every rule block are valid IPv4 CIDR strings with prefix length from
0to32. - The number of rules is moderate (the intended solution is quadratic in the number of rules at worst).
- Do not enumerate individual addresses; a block can contain up to 2^32 addresses.
- Return a boolean.
Examples
Example 1
Input: is_block_cleared('10.0.0.0/30', [['allow', '10.0.0.0/31'], ['allow', '10.0.0.2/31']])
Output: True
Example 2
Input: is_block_cleared('10.0.0.0/30', [['allow', '10.0.0.0/31'], ['deny', '10.0.0.2/31']])
Output: False
Example 3
Input: is_block_cleared('192.168.1.0/24', [['allow', '192.168.0.0/16']])
Output: True
Hints
Hint 1
Every CIDR block is a contiguous range of 32-bit integers, from its network address to its broadcast address. Convert blocks to [start, end] integer pairs.
Hint 2
Store the uncleared region as a list of disjoint closed intervals. A deny rule fires if its interval overlaps any stored interval, which is when left <= rule_end and rule_start <= right.
Hint 3
Subtracting [rule_start, rule_end] from [left, right] leaves at most two pieces: [left, rule_start - 1] if left < rule_start, and [rule_end + 1, right] if rule_end < right. Once the list is empty, the answer is true.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
An IPv4 CIDR block is a contiguous range of 32-bit integers: from the network address (host bits zero) up to the broadcast address (host bits one). So the whole problem becomes interval arithmetic, and no address ever needs to be enumerated.
- Convert the target to a closed interval
[start, end]. The uncleared region starts as the list containing just this interval. - For each rule, convert its block to
[rs, re]. Parsing withipaddress.IPv4Network(..., strict=False)normalizes blocks that have host bits set. - Deny: if
[rs, re]overlaps any interval[left, right]in the list (that is,left <= reandrs <= right), returnFalse. - Allow: subtract
[rs, re]from every interval. A non-overlapping interval is kept as is. An overlapping one leaves a left piece[left, rs - 1](ifleft < rs) and a right piece[re + 1, right](ifre < right). - If the list becomes empty, return
Trueimmediately. After all rules, return whether the list is empty.
Why it is correct
- A CIDR block with prefix
xis exactly the integers in[net, net + 2^(32-x) - 1], so overlap and removal on addresses are the same as overlap and removal on these intervals. - The list always holds disjoint intervals whose union is exactly the uncleared region. Subtraction only produces sub-pieces of an existing interval, so disjointness is preserved.
- A deny overlaps the region if and only if it overlaps at least one of the disjoint pieces, so the check is exact. Because rules are processed in order, the deny sees the region as it stands at that point; a deny before a covering allow fails, while a deny after full clearance cannot fire.
- Once the region is empty, no later allow changes it and no later deny can overlap it, so returning
Trueearly gives the same result as finishing the loop. - Pieces created by subtraction need not be CIDR-aligned, which is fine because only the integer endpoints matter.
Complexity
With n rules, a single contiguous allow range can split at most one interval into two, so the list never exceeds n + 1 intervals. Each rule scans the list once, giving O(n^2) time in the worst case and O(n) space. Keeping the intervals sorted and using binary search could reduce this further, but the linear scan is sufficient here.
Reference solution
import ipaddress
from typing import List
def is_block_cleared(target: str, rules: List[List[str]]) -> bool:
net = ipaddress.IPv4Network(target, strict=False)
remaining = [(int(net.network_address), int(net.broadcast_address))]
for kind, cidr in rules:
rule_net = ipaddress.IPv4Network(cidr, strict=False)
rs = int(rule_net.network_address)
re_ = int(rule_net.broadcast_address)
if kind == "deny":
for left, right in remaining:
if left <= re_ and rs <= right:
return False
else:
updated = []
for left, right in remaining:
if re_ < left or right < rs:
updated.append((left, right))
else:
if left < rs:
updated.append((left, rs - 1))
if re_ < right:
updated.append((re_ + 1, right))
remaining = updated
if not remaining:
return True
return not remaining