Evaluate IP Access Rules
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Overview: This question evaluates knowledge of IPv4 addressing, CIDR subnet matching, and access-control rule resolution, assessing competency in bitwise address reasoning, prefix-length precedence, and rule tie-breaking.
Constraints
- 0 <= number of rules <= 10^5
- Each CIDR prefix length is in the range 0 to 32
- All IPs and CIDR blocks are valid IPv4 (no IPv6)
- action is exactly "allow" or "deny"
Examples
Input: ([['allow', '192.168.0.0/16'], ['deny', '192.168.1.0/24']], '192.168.1.25')
Expected Output: 'deny'
Explanation: Both rules match. /24 is a longer prefix than /16, so the deny rule wins.
Input: ([['deny', '0.0.0.0/0'], ['allow', '10.0.0.0/8']], '10.1.2.3')
Expected Output: 'allow'
Explanation: The /0 default deny and the /8 allow both match; the longer /8 prefix wins -> allow.
Hints
- Convert each dotted-quad IPv4 address to a 32-bit integer so containment becomes a bitmask test.
- For a prefix length p, build the mask ((1 << p) - 1) << (32 - p); a rule matches when (target & mask) == (network & mask). Handle p == 0 specially (mask = 0, matches everything).
- Track the longest prefix length seen so far. Use '>=' (not '>') when comparing so that a rule with an equal prefix length that appears later overrides the earlier one.