Find first CIDR block covering IP
Company: Databricks
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's understanding of IPv4 and CIDR notation, ability to perform prefix-based address containment checks using bitwise reasoning, and competence in parsing and efficient lookup across many ranges.
Constraints
- 0 <= len(cidr_blocks) <= 10^5
- Each IPv4 address has exactly 4 octets, and each octet is between 0 and 255
- Each prefix length x satisfies 0 <= x <= 32
- All input strings are syntactically valid IPv4 and CIDR strings
Examples
Input: ("192.168.1.5", ["10.0.0.0/8", "192.168.1.0/24", "192.168.0.0/16"])
Expected Output: "192.168.1.0/24"
Explanation: The IP does not match 10.0.0.0/8, but it does match 192.168.1.0/24. Even though it also matches 192.168.0.0/16, the first match must be returned.
Input: ("10.1.2.3", ["10.0.0.0/8", "10.1.2.0/24"])
Expected Output: "10.0.0.0/8"
Explanation: Both CIDR blocks contain the IP, but the first matching block in list order is 10.0.0.0/8.
Hints
- Convert each IPv4 address into a 32-bit integer so prefix comparisons become simple bit operations.
- For a CIDR prefix length x, build a mask with x leading 1 bits. Two addresses are in the same block if their masked values are equal.