IP Firewall
DatabricksPhone screenMedium
You are given a list of firewall rules for IPv4 addresses. Each rule is a pair [action, target] where action is "ALLOW" or "DENY". A target is either a single address such as "192.168.1.9" or a network such as "10.5.12.10/28".
A network a.b.c.d/p covers every address whose first p bits equal the first p bits of a.b.c.d. Bits of a.b.c.d after the first p are ignored, so 10.5.12.10/28 covers 10.5.12.0 through 10.5.12.15. A single address covers only itself, and /0 covers every address.
Implement the Firewall class:
class Firewall:
def __init__(self, rules: list[list[str]]) -> None: ...
def check(self, ip: str) -> bool: ...
def shadowed(self, index: int) -> bool: ...Each test builds one Firewall and calls its methods in order.
Part 1: First matching rule
Implement check(ip), where ip is a dotted IPv4 address string.
Go through the rules in order. The first rule whose target covers ip decides the result: return True for "ALLOW" and False for "DENY". Later rules are never looked at, even when they are more specific. If no rule covers ip, return False.
- Example 1
- init
[[["ALLOW","192.168.1.9"],["DENY","192.168.1.0/24"],["ALLOW","10.5.12.10/28"],["DENY","0.0.0.0/0"]]]- operations
[["check",["192.168.1.9"]],["check",["192.168.1.10"]],["check",["10.5.12.0"]],["check",["10.5.12.15"]],["check",["10.5.12.16"]],["check",["8.8.8.8"]]]- Output
[true,false,true,true,false,false]
Why: 192.168.1.9 matches the first rule exactly, so it is allowed even though the next rule denies its whole /24. 192.168.1.10 skips the first rule and is denied by the /24. 10.5.12.10/28 covers 10.5.12.0 to 10.5.12.15, so .0 and .15 are allowed and .16 falls through to the final DENY. 8.8.8.8 matches only the final rule.
Constraints
0 <= len(rules) <= 10^50 <= p <= 32for every networka.b.c.d/p- every address is four decimal numbers from
0to255separated by dots 1 <= len(operations) <= 10^4