Aggregate Two Adjacent Subnets
Problem Statement
Route summarization merges two adjacent equal-size subnets into a single shorter-prefix block when possible. Given two CIDRs of the same prefix length, return their aggregate CIDR or None if they cannot be merged.
Background
Two /p blocks aggregate into a /(p-1) block only if they are the two halves of that parent: same prefix length, and the parent's base (the /(p-1) network of the lower block) exactly contains both, with the two blocks being consecutive and non-overlapping. Concretely, they merge iff base1 % (2*size) == 0 (lower block aligned to the parent) and base2 == base1 + size, where size = 2(32-p)**.
Your Task
def aggregate(cidr_a, cidr_b):
Return the aggregated "network/prefix" string, or None.
Input Format
- cidr_a, cidr_b (str), same prefix length.
Output Format
- A CIDR string or None.
Sample
print(aggregate("10.0.0.0/24", "10.0.1.0/24"))
Output:
10.0.0.0/23
Example
print(aggregate("10.0.0.0/24", "10.0.1.0/24"))10.0.0.0/23
-
Parse and Convert: Convert the IP addresses to 32-bit integers to facilitate arithmetic.
- Both have prefix length .
-
Determine Block Size: Calculate the number of addresses in a single subnet.
-
Identify Lower and Upper Blocks: Sort the integer values to determine adjacency.
-
Check Merge Conditions: Verify that the lower block is aligned to the parent boundary and the blocks are consecutive.
- Alignment: (Aligned)
- Adjacency: (True)
-
Construct Result: Since conditions are met, the aggregate network is the lower block with the prefix length decremented by 1.
- Network:
- New Prefix:
- The final output is
10.0.0.0/23
Constraints
- Both must share the prefix length
p. - Merge only if the lower base is aligned to
2*sizeand the upper base is exactlysizehigher. - Return the
/(p-1)CIDR, else None.