Find first CIDR block covering IP
DatabricksSoftware Engineer · Technical ScreenLast updated
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.
You are given:
- A single IPv4 address as a string, e.g.
"192.168.1.5". - A list of CIDR blocks (IPv4), each as a string in the form
"a.b.c.d/x", where0 <= a,b,c,d <= 255and0 <= x <= 32.
Each CIDR block a.b.c.d/x represents all IP addresses whose first x bits are identical to the first x bits of the base address a.b.c.d.
Task:
Return the first CIDR block in the given list that covers (contains) the given IP address. If none of the CIDR blocks contains the IP, return some designated value such as null or an empty string.
Clarifications:
- "First" means the first element in the input list order that matches.
- Assume IPv4 only.
- You may assume the input strings are syntactically valid.
- Aim for an efficient solution that can handle up to, for example, 10^5 CIDR blocks.
Define clearly what you return when there is no matching CIDR.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.