KatInterview

IP Access Control with CIDR Matching

Data Structure DesignAuto-graded · 17 test cases
HardAuto-gradedData Structure Designtriebit-manipulationnetwork-programming

Last 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 return None
  • "is_allowed": return True if the IP matches any stored rule, otherwise False

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_rule may be called up to 100,000 times
  • is_allowed must run in time independent of the number of stored rules
  • If an operation name is neither "add_rule" nor "is_allowed", raise ValueError
  • 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