IP Access Control with CIDR Matching
Data Structure DesignAuto-graded · 17 test casesLast updated
Tests binary trie implementation for efficient IP prefix matching with CIDR notation and rule subsumption optimization.
Build a system that checks whether IP addresses match stored access rules. Rules can be either exact IP addresses (like 192.168.1.1) or CIDR blocks (like 192.168.1.0/24), which represent ranges of addresses sharing a common prefix.
Your function receives two parallel lists describing a sequence of operations:
operations[i]is either"add_rule"or"is_allowed"arguments[i]contains a single string: the rule to add or the IP to check
For each operation, produce an output:
"add_rule": store the given rule and returnNone"is_allowed": returnTrueif the IP matches any stored rule, otherwiseFalse
An IP matches a CIDR rule X/k when its first k bits equal the first k bits of X. An IP without a prefix (like 192.168.1.5) is treated as a /32 rule matching only itself.
Constraints
- All addresses are IPv4 (four octets, each 0-255)
add_rulemay be called up to 100,000 timesis_allowedmust run in time independent of the number of stored rules- If an operation name is neither
"add_rule"nor"is_allowed", raiseValueError - CIDR notation may include host bits (e.g.,
192.168.1.5/24); normalize to the network address (192.168.1.0/24)
Examples
Example 1
Input: check_ip_access(['add_rule', 'is_allowed', 'is_allowed'], [['10.0.0.0/8'], ['10.5.5.5'], ['192.168.1.1']])
Output: [None, True, False]
Example 2
Input: check_ip_access(['add_rule', 'is_allowed'], [['192.168.1.5'], ['192.168.1.5']])
Output: [None, True]
Hints
Hint 1
Convert each IP address to a 32-bit integer and work with individual bits from most significant to least significant
Hint 2
A CIDR block X/k matches all addresses whose top k bits match X's top k bits—this is a prefix match problem
Hint 3
Use a binary trie where each path represents a bit prefix; mark nodes as terminal when they correspond to stored rules
Hint 4
When adding a broader rule that subsumes existing narrower rules, prune the redundant subtrees to maintain efficiency
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Convert each IP address to a 32-bit integer (four octets packed as a·2²⁴ + b·2¹⁶ + c·2⁸ + d). A CIDR rule X/k represents all addresses whose top k bits match X, making this a prefix matching problem.
Store rules in a binary trie where each edge represents a bit (0 or 1) and each node may be marked as terminal. Inserting X/k means walking k bits from the most significant bit, creating nodes as needed, then marking the final node terminal.
To check if an IP is allowed, walk its 32 bits through the trie. If you reach a terminal node, a rule matches. If you fall off the trie (missing child), no rule matches.
Optimization: Rule Subsumption
When a broader rule is added after narrower ones (e.g., 10.0.0.0/8 after 10.1.0.0/16), delete the narrower subtree since it's now redundant. When a narrower rule is added after a broader one, stop early since the broader rule already covers it. This maintains the invariant that terminal nodes are leaves, keeping the trie compact and queries fast.
Correctness
Each rule corresponds to a unique node at depth equal to its prefix length. During a query, we visit every node representing a prefix of the IP. The first terminal node we hit represents a matching rule. Pruning redundant rules never changes query results because discarded rules are always covered by broader ones.
Complexity
- Time per add_rule: O(32) = O(1), walking up to prefix_length bits
- Time per is_allowed: O(32) = O(1), independent of the number of rules
- Space: O(32N) nodes worst case, but typically much less due to shared prefixes and pruning
The constant-time query satisfies the requirement to avoid O(N) scanning.
Edge Cases
- A
/0rule marks the root terminal and makes all subsequent queries returnTrue - Overlapping rules in either order are handled by the two pruning cases
- Duplicate rules harmlessly re-mark nodes
- CIDR notation with host bits is normalized to the network address
- Plain IP addresses are treated as
/32rules
import ipaddress
from typing import List, Optional
def check_ip_access(operations: List[str], arguments: List[List[str]]) -> List[Optional[bool]]:
# Trie node structure: [children_dict, is_terminal_flag]
root = [{}, False]
output = []
for op, args in zip(operations, arguments):
if op == "add_rule":
net = ipaddress.ip_network(args[0], strict=False)
addr_int = int(net.network_address)
current = root
# Skip if root already matches everything
if current[1]:
output.append(None)
continue
# Walk down the trie for prefix_length bits
for i in range(net.prefixlen):
bit_val = (addr_int >> (31 - i)) & 1
if bit_val not in current[0]:
current[0][bit_val] = [{}, False]
current = current[0][bit_val]
# Stop if we hit an existing broader rule
if current[1]:
break
# Mark this node as terminal and clear any narrower rules
current[1] = True
current[0].clear()
output.append(None)
elif op == "is_allowed":
addr_int = int(ipaddress.IPv4Address(args[0]))
current = root
matched = current[1]
# Walk all 32 bits looking for a terminal node
for i in range(32):
bit_val = (addr_int >> (31 - i)) & 1
if bit_val not in current[0]:
break
current = current[0][bit_val]
if current[1]:
matched = True
break
output.append(matched)
else:
raise ValueError("Unknown operation")
return output