Detect Overlapping CIDR Blocks
Problem Statement
Before peering VPCs, check whether any two CIDR blocks overlap (which would break routing). Return whether the given set of blocks is conflict-free.
Background
Each CIDR maps to an integer address range [network_base, network_base + 2(32-prefix) - 1]** where network_base is the network address with host bits zeroed. Two ranges overlap if start1 <= end2 and start2 <= end1. The set is valid if no pair overlaps.
Your Task
def has_overlap(cidrs):
- cidrs: list of "network/prefix" strings.
- Return True if any two blocks overlap, else False.
Input Format
- cidrs (list of str).
Output Format
- A boolean.
Sample
print(has_overlap(["10.0.0.0/16", "10.0.1.0/24"]))
Output:
True
Example
print(has_overlap(["10.0.0.0/16", "10.0.1.0/24"]))
True
- Convert the first CIDR
10.0.0.0/16to an integer range. The IP10.0.0.0converts to the integer . With a prefix of 16, the block size is . The network base is (host bits are already zero), so the range is . - Convert the second CIDR
10.0.1.0/24to an integer range. The IP10.0.1.0converts to the integer . With a prefix of 24, the block size is . The network base is , so the range is . - Sort the ranges by their starting addresses to facilitate efficient comparison. The ranges are already in order: followed by .
- Check for overlap between adjacent ranges. Compare the start of the second range () with the end of the first range (). Since , the condition for overlap is met.
- The final output is True
Constraints
- Zero host bits to get the true network base.
- Ranges overlap iff
start1 <= end2 and start2 <= end1. - Return True if any pair overlaps.