PIXELBANKv9.1.0
Menu

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:

Input:
print(aggregate("10.0.0.0/24", "10.0.1.0/24"))
Output:
10.0.0.0/23
Reasoning:
  • Parse and Convert: Convert the IP addresses to 32-bit integers to facilitate arithmetic.

    • 10.0.0.0β†’10β‹…224=167,772,16010.0.0.0 \rightarrow 10 \cdot 2^{24} = 167,772,160
    • 10.0.1.0β†’10β‹…224+1β‹…216=167,774,20810.0.1.0 \rightarrow 10 \cdot 2^{24} + 1 \cdot 2^{16} = 167,774,208
    • Both have prefix length p=24p = 24.
  • Determine Block Size: Calculate the number of addresses in a single /24/24 subnet.

    • size=232βˆ’24=28=256\text{size} = 2^{32 - 24} = 2^8 = 256
  • Identify Lower and Upper Blocks: Sort the integer values to determine adjacency.

    • lo=167,772,160\text{lo} = 167,772,160
    • hi=167,774,208\text{hi} = 167,774,208
  • Check Merge Conditions: Verify that the lower block is aligned to the parent boundary and the blocks are consecutive.

    • Alignment: lo(mod2β‹…size)=167,772,160(mod512)=0\text{lo} \pmod{2 \cdot \text{size}} = 167,772,160 \pmod{512} = 0 (Aligned)
    • Adjacency: hi=lo+sizeβ†’167,774,208=167,772,160+256\text{hi} = \text{lo} + \text{size} \rightarrow 167,774,208 = 167,772,160 + 256 (True)
  • Construct Result: Since conditions are met, the aggregate network is the lower block with the prefix length decremented by 1.

    • Network: 10.0.0.010.0.0.0
    • New Prefix: 24βˆ’1=2324 - 1 = 23
    • 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*size and the upper base is exactly size higher.
  • Return the /(p-1) CIDR, else None.
πŸ”’

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.