← 返回 databricks 的题目列表Ordered CIDR Firewall Rules Match (First Hit Wins)
类型:online_judge
You are given an ordered list of access-control rules rules. Each rule contains:
pattern: either a single IPv4 address (e.g., "8.8.8.8") or a CIDR block (e.g., "192.168.1.0/24")
status: a string such as "ALLOW" or "DENY"
Implement get_status(rules, ip):
Input: the rule list rules and a query IPv4 string ip (e.g., "192.168.1.5")
Output: return the status of the first rule that matches the given ip (first-hit wins because rules is ordered)
Matching rules:
If pattern is a single IPv4 (no /), it matches iff it equals ip.
If pattern is CIDR A/B (e.g., 192.168.1.0/24):
Convert IPv4 to a 32-bit binary (or equivalent integer form)
B is the prefix length (0..32); the first B bits must match
It matches if the first B bits of ip equal the first B bits of A
Assumptions:
rules contains at least one rule.
All IP strings are valid IPv4 dotted-decimal.
Example:
rules = [
("192.168.1.0/24", "ALLOW"),
("8.8.8.8", "DENY"),
]
get_status(rules, "192.168.1.5") -> "ALLOW"
Constraints (suggested):
1 <= len(rules) <= 1e5
Consider efficiency for large rule sets.
Provide an implementation and analyze time complexity.
Example
Input
2
192.168.1.0/24 ALLOW
8.8.8.8 DENY
192.168.1.5
Output
ALLOW