Build a Dynamic IP Address Filter with CIDR and Range Support
Data Structure DesignModel answerLast updated
Implement a low-latency IP rule matcher supporting CIDR blocks and numeric ranges with conflict resolution based on specificity and recency.
You need to build a system that determines whether to allow or block IPv4 addresses based on configurable rules. Each rule specifies an action (accept or deny) and applies to either:
- A CIDR block (e.g.,
192.168.0.0/16) - An inclusive IP range (e.g.,
10.0.0.1-10.0.0.50) - A single IP address
Your implementation must support three operations:
addRule(action, specification)— Register a new ruleremoveRule(action, specification)— Delete the most recently added matching rulequery(ip)— Return"accept"or"deny"for the given IP
When multiple rules match an IP address, apply these tiebreakers in order:
- Specificity: Prefer the rule covering the smallest address range
- Recency: If ranges are equal in size, prefer the most recently added rule
- Default: If no rules match, return
"deny"
Your design should handle up to 100,000 rules efficiently with low query latency.
Provide:
- Data structure choices and their rationale
- Implementation with time and space complexity analysis
- Discussion of edge cases (especially around bitwise operations and IP parsing)
- Comparison of alternative approaches for this problem
Hints
Hint 1
Any numeric IP range can be decomposed into a small set of aligned CIDR blocks — this makes indexing much easier
Hint 2
Use a min-heap per CIDR block keyed by (original_rule_size, -rule_timestamp) to efficiently find the best matching rule
Hint 3
An IP address belongs to exactly one CIDR block at each prefix length (0 through 32), so checking all 33 possible blocks covers every applicable rule
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
The core challenge is efficiently matching arbitrary IP ranges while supporting dynamic updates. The key insight is to normalize all rules into CIDR blocks, which have predictable structure.
Strategy
Range Decomposition: Convert every IP range into a minimal set of non-overlapping CIDR blocks. Any range [start, end] can be expressed as at most 62 aligned CIDR blocks by repeatedly selecting the largest power-of-two block that fits.
Indexing Structure: Maintain a hash table where each key is (prefix_length, network_address) representing a CIDR block. The value is a min-heap containing all rules that cover that block, ordered by (original_range_size, -rule_id).
Query Process: For a given IP, determine the unique CIDR block it belongs to at each prefix length (0 through 32). Look up each block in the hash table and collect the minimum entry from each heap. The global minimum across all heaps is the winning rule.
Lazy Deletion: When removing a rule, mark its rule ID as deleted rather than searching through heaps. During queries, skip deleted entries at the top of heaps.
Why This Works
- Coverage Guarantee: The decomposition partitions ranges exactly, so an IP matches a rule if and only if it lies in one of the rule's CIDR fragments
- Correctness: Checking all 33 prefix lengths ensures we examine every relevant rule
- Proper Conflict Resolution: The heap ordering
(size, -id)directly implements specificity-then-recency - Efficiency: Hash lookups are O(1), and heap operations are logarithmic in the number of rules per block
Complexity Analysis
For n rules (up to 100,000):
addRule: O(62 log n) worst case — each range produces at most 62 CIDR blocks, each requiring a heap push. Most real rules (pure CIDRs) complete in O(log n).removeRule: O(1) — just mark the rule as deletedquery: O(33) expected — 33 hash lookups plus amortized heap cleanup. Deleted entries at heap tops are removed lazily.- Space: O(62n) worst case if all rules are adversarial ranges. Practical workloads with mostly CIDR rules use O(n) space.
Edge Cases and Pitfalls
Operator Precedence: In most languages, comparison operators bind tighter than bitwise operators. The expression ip & mask == network parses as ip & (mask == network), which is wrong. Always use (ip & mask) == network.
Shift Edge Cases:
/0(matches all IPs) has a 32-bit shift. In some languages, shifting by the word size is undefined. Handle this explicitly./32represents a single IP with mask0xFFFFFFFF
IP Parsing Concerns:
- Reject octets greater than 255
- Reject leading zeros (e.g.,
192.168.001.1should fail to avoid octal interpretation confusion) - Validate exactly four octets
Boundary Values: Test 0.0.0.0, 255.255.255.255, and ranges that span the entire address space.
Duplicate Rules: Adding the same rule twice creates two instances. Removing it once eliminates only the newest.
Implementation
import heapq
def parse_ip(s: str) -> int:
parts = s.strip().split(".")
if len(parts) != 4:
raise ValueError(f"Invalid IP: {s}")
result = 0
for part in parts:
if not part.isdigit() or (len(part) > 1 and part[0] == "0"):
raise ValueError(f"Invalid octet: {part}")
octet = int(part)
if octet > 255:
raise ValueError(f"Octet out of range: {part}")
result = (result << 8) | octet
return result
def parse_spec(spec: str) -> tuple[int, int]:
spec = spec.strip()
if "/" in spec:
ip_part, prefix_len_part = spec.split("/")
prefix_len = int(prefix_len_part)
if not 0 <= prefix_len <= 32:
raise ValueError("Prefix length out of range")
ip = parse_ip(ip_part)
host_bits = 32 - prefix_len
mask = (0xFFFFFFFF << host_bits) & 0xFFFFFFFF if host_bits < 32 else 0xFFFFFFFF
network = ip & mask
broadcast = network | ((1 << host_bits) - 1) if host_bits > 0 else network
return network, broadcast
elif "-" in spec:
start_ip, end_ip = spec.split("-")
start = parse_ip(start_ip)
end = parse_ip(end_ip)
if start > end:
raise ValueError("Invalid range: start > end")
return start, end
else:
ip = parse_ip(spec)
return ip, ip
def decompose_range(start: int, end: int):
"""Yield (prefix_length, network_address) for all CIDR blocks covering [start, end]."""
while start <= end:
# Find the largest aligned block starting at 'start' that fits within 'end'
max_block = 1 << 32
while max_block > 1 and (start & (max_block - 1)) != 0:
max_block >>= 1
while start + max_block - 1 > end:
max_block >>= 1
prefix_len = 32 - (max_block.bit_length() - 1)
yield prefix_len, start
start += max_block
class IPRuleMatcher:
def __init__(self, default_action: str = "deny"):
self.default_action = default_action
self._next_id = 0
self._active_rules = {} # rule_id -> (start, end, action)
self._rule_index = {} # (start, end, action) -> [rule_ids]
self._cidr_heaps = {} # (prefix_len, network) -> heap of (range_size, -rule_id)
def addRule(self, action: str, spec: str) -> int:
if action not in ("accept", "deny"):
raise ValueError(f"Invalid action: {action}")
start, end = parse_spec(spec)
rule_id = self._next_id
self._next_id += 1
self._active_rules[rule_id] = (start, end, action)
self._rule_index.setdefault((start, end, action), []).append(rule_id)
range_size = end - start + 1
heap_entry = (range_size, -rule_id)
for prefix_len, network in decompose_range(start, end):
heap = self._cidr_heaps.setdefault((prefix_len, network), [])
heapq.heappush(heap, heap_entry)
return rule_id
def removeRule(self, action: str, spec: str) -> bool:
start, end = parse_spec(spec)
rule_list = self._rule_index.get((start, end, action))
if not rule_list:
return False
rule_id = rule_list.pop()
if not rule_list:
del self._rule_index[(start, end, action)]
del self._active_rules[rule_id]
return True
def query(self, ip: str) -> str:
ip_int = parse_ip(ip)
best_match = None
for prefix_len in range(33):
host_bits = 32 - prefix_len
if host_bits < 32:
network = (ip_int >> host_bits) << host_bits
else:
network = 0
heap = self._cidr_heaps.get((prefix_len, network))
if heap is None:
continue
# Clean up deleted entries at the top
while heap and -heap[0][1] not in self._active_rules:
heapq.heappop(heap)
if not heap:
del self._cidr_heaps[(prefix_len, network)]
continue
if best_match is None or heap[0] < best_match:
best_match = heap[0]
if best_match is None:
return self.default_action
rule_id = -best_match[1]
return self._active_rules[rule_id][2]
Alternative Approaches
Interval Tree: Supports O(log n + k) range queries where k is the number of overlapping intervals. Good for static rule sets but insertion/deletion is more complex.
Segment Tree: Allows O(log n) updates and queries but requires discretization of the IP space or lazy propagation. Space overhead is higher.
Sorted List with Binary Search: Simple for static rules (O(log n) query with binary search to find all overlapping ranges). Dynamic updates require maintaining sorted order.
Radix Trie: Natural for prefix matching with O(32) lookup. Excellent for pure CIDR rules but arbitrary ranges still require decomposition.
The CIDR decomposition with heap-per-block approach balances query speed, update flexibility, and implementation simplicity, making it well-suited for this problem's requirements.