Ordered IPv4 Access List: Verdict for an Address or Entire Subnet
Math & Bit ManipulationAuto-graded · 30 test casesLast updated
Evaluate an ordered first-match IPv4 access list for a single address or a whole CIDR block, which needs prefix arithmetic and interval reasoning rather than enumerating addresses.
You are given an access list: an ordered sequence of entries, each pairing an IPv4 pattern with a verdict ("ALLOW" or "DENY"). For example:
acl = [("192.168.1.0/24", "ALLOW"), ("8.8.8.8", "DENY")]
Your task is to decide whether a given target is allowed.
Patterns
- A pattern of the form
a.b.c.d/pis a CIDR block. It covers every address whose leadingpbits equal the leadingpbits ofa.b.c.d. - A pattern with no
/is a single address and behaves exactly like/32. - Treat an address as a 32-bit unsigned integer, with the first octet as the most significant byte.
/0covers every address.- Bits of the written address beyond the first
pare ignored. For example,10.0.0.5/24behaves exactly like10.0.0.0/24.
Verdict of one address
The verdict of an address is the verdict of the earliest entry in the list (lowest index) whose pattern covers it. If no entry covers the address, its verdict is "DENY".
The target
The target is either a bare address (a block holding exactly one address) or a CIDR block a.b.c.d/q, which stands for every address whose first q bits match those of a.b.c.d.
Return "ALLOW" if every address in the target block has verdict "ALLOW". Otherwise return "DENY". For a bare address, this is simply that address's verdict.
Note that a block can fail either because some address in it hits a DENY entry first, or because some address in it is not covered by any entry at all.
Constraints
1 <= len(acl) <= 10^5- Every prefix length, in an entry or in the target, is an integer from 0 to 32. A pattern with no
/means/32. - Every address is four decimal octets from 0 to 255 separated by dots, with no leading zeros or whitespace.
- Every verdict is exactly
"ALLOW"or"DENY". - A target block may contain up to
2^32addresses, so checking addresses one by one is not feasible. - The return value is exactly
"ALLOW"or"DENY".
Examples
Example 1
Input: evaluate_access([['192.168.1.0/24', 'ALLOW'], ['8.8.8.8', 'DENY']], '192.168.1.5')
Output: 'ALLOW'
Example 2
Input: evaluate_access([['10.0.0.7', 'DENY'], ['10.0.0.0/24', 'ALLOW']], '10.0.0.0/28')
Output: 'DENY'
Example 3
Input: evaluate_access([['10.0.0.0/25', 'ALLOW'], ['10.0.0.128/25', 'ALLOW']], '10.0.0.0/24')
Output: 'ALLOW'
Hints
Hint 1
Any two CIDR blocks are either nested (one contains the other) or completely disjoint. They never partially overlap.
Hint 2
Split the entries by size relative to the target. Entries at least as large as the target either contain all of it or none of it, and only the earliest containing one matters. Entries strictly smaller are either fully inside the target or irrelevant.
Hint 3
Sort the relevant smaller blocks by (start, prefix length) and walk them with a stack that holds the current chain of nested blocks. For each block, compare the total size of its direct children against its own size to detect addresses not covered by any child, and carry the minimum entry index along the chain.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A target such as /0 contains 2^32 addresses, so we cannot test each one. Instead we use the fact that two CIDR blocks are either nested or disjoint. Hence the blocks form a tree, and we reason about tree nodes rather than addresses.
Let the target be T with prefix length tl. Classify every entry by its prefix length rl:
rl <= tl(at least as large asT). The entry either contains all ofTor none of it. Among those that containT, only the earliest one matters. Call it the root entry. If there is none, the root behaves as an implicitDENYwith index infinity, which matches the rule for uncovered addresses.rl > tl(strictly smaller thanT). The entry is either entirely insideTor entirely outside it. Keep the ones inside. If the same normalized block appears several times, keep only the first occurrence, since later duplicates can never be the first match.
The root plus the inner blocks form a tree. For an address x in T, the entries covering it are the root entry plus the inner blocks on the chain from the top down to the deepest block containing x. Its verdict is the verdict of the minimum-index entry on that chain.
Group addresses by their deepest containing node B. They are the addresses of B not covered by any child of B, and they all share the same chain, hence the same verdict. So the answer is "DENY" exactly when some node has uncovered addresses and its chain-minimum verdict is DENY.
To traverse, sort inner blocks by (start, prefix_len). A parent then precedes its children, giving a pre-order walk. A stack holds the current chain, and each frame stores:
end: the exclusive end of the block's range,size: the number of addresses in the block,child_sum: the total size of direct children (children are disjoint, sochild_sum < sizemeans some address is uncovered),- the best
(index, verdict)along the chain so far.
When the next block starts at or after the top frame's end, it cannot lie inside that frame, so we pop it and check it. Otherwise it lies inside the top frame, so we add its size to child_sum, combine the best index, and push it.
Why it is correct
- Root entry: an entry at least as large as
Tcovers either all or none ofT, so only the earliest covering one can ever be the first match for addresses ofT. Entries disjoint fromTmatch nothing in it. - Chain minimum: blocks containing a given address are totally ordered by nesting, and the stack is exactly that chain. Carrying the minimum index down the stack yields the first-match entry for every address whose deepest block is that node.
- Partition: every address in
Thas exactly one deepest containing node, so checking "has uncovered addresses and the verdict is DENY" at each node considers every address exactly once.
Edge cases fall out naturally: host bits are cleared when parsing, duplicates keep only the earliest index, an entry equal to the target becomes the root entry, and with no matching entries the implicit root DENY rejects any uncovered address.
Complexity
- Time: O(n log n), dominated by sorting the inner blocks. Parsing and classification are O(n), and each block is pushed and popped once. The cost does not depend on the target's size.
- Space: O(n) for the dictionary of inner blocks and the stack.
Reference solution
from typing import List, Tuple
def evaluate_access(acl: List[Tuple[str, str]], target: str) -> str:
def parse(p):
addr, _, length = p.partition('/')
length = int(length) if length else 32
o1, o2, o3, o4 = addr.split('.')
v = (int(o1) << 24) | (int(o2) << 16) | (int(o3) << 8) | int(o4)
base = ((v >> (32 - length)) << (32 - length)) if length else 0
return base, length
t_start, t_len = parse(target)
INF = float('inf')
root_idx, root_act = INF, "DENY"
inner = {}
for idx, (pat, action) in enumerate(acl):
r_start, r_len = parse(pat)
if r_len <= t_len:
# Entry is at least as large as the target: contains it or misses it.
if root_idx == INF:
masked = ((t_start >> (32 - r_len)) << (32 - r_len)) if r_len else 0
if masked == r_start:
root_idx, root_act = idx, action
else:
# Entry is strictly smaller: inside the target or disjoint from it.
masked = ((r_start >> (32 - t_len)) << (32 - t_len)) if t_len else 0
if masked == t_start and (r_start, r_len) not in inner:
inner[(r_start, r_len)] = (idx, action)
# Frame: [end (exclusive), size, sum of direct-children sizes, best idx, best action]
total = 1 << (32 - t_len)
stack = [[t_start + total, total, 0, root_idx, root_act]]
for (r_start, r_len) in sorted(inner):
while stack[-1][0] <= r_start:
frame = stack.pop()
if frame[2] < frame[1] and frame[4] == "DENY":
return "DENY"
top = stack[-1]
size = 1 << (32 - r_len)
top[2] += size
idx, act = inner[(r_start, r_len)]
if top[3] < idx:
idx, act = top[3], top[4]
stack.append([r_start + size, size, 0, idx, act])
while stack:
frame = stack.pop()
if frame[2] < frame[1] and frame[4] == "DENY":
return "DENY"
return "ALLOW"