Merged IP view

Difficulty: MEDIUMCategory: DSAFrequency: 1Asked On 2025-05-01

Problem Statement

Question:

Given a list of IP addresses with their subnets in CIDR notation (e.g., "192.168.0.1/24"), group the IPs such that any two IPs that belong to the same subnet are considered connected. If an IP is connected to another IP either directly (same subnet) or indirectly (via transitive subnet connections), they should be grouped into the same cluster.

Example:

1input = [ 2 "192.168.1.1/24", 3 "192.168.1.2/24", 4 "192.168.2.1/24", 5 "192.168.3.1/16" 6]

Explanation:

•"192.168.1.1/24" and "192.168.1.2/24" are in the same /24 subnet → same group.
•"192.168.3.1/16" covers the entire range of 192.168.x.x, so it connects with both "192.168.1.x" and "192.168.2.x".
•Thus, all IPs are connected through "192.168.3.1/16".

Expected Output:

1[ 2 ["192.168.1.1/24", "192.168.1.2/24", "192.168.2.1/24", "192.168.3.1/16"] 3]

Or in a case with disconnected groups:

1input = [ 2 "10.0.0.1/24", 3 "10.0.0.2/24", 4 "192.168.1.1/24", 5 "172.16.0.1/16" 6]

Expected Output:

1[ 2 ["10.0.0.1/24", "10.0.0.2/24"], 3 ["192.168.1.1/24"], 4 ["172.16.0.1/16"] 5]


Solution

The solution is straightforward:

1.Convert each IP/subnet into a numeric range:
•Parse the IP and subnet.
•Compute the start and end of the IP range, and represent them as integers (using 32-bit integer format for IPv4).
•This numeric form makes it easier to sort and compare ranges.
2.Sort all the IP ranges based on their start values.
3.Merge overlapping or adjacent ranges by scanning left to right. Two ranges are merged if they overlap or touch (i.e., start2 <= end1 + 1).
4.Group the original IPs based on which merged interval they fall into.

Why convert to integers?

Working with IPs as strings or dotted quads (e.g., 192.168.0.1) is not efficient for range comparison. By converting them to integers (e.g., 192.168.0.1 → 3232235521), we can perform numeric range operations, which are faster and easier to reason about.

Example 1: All connected

1input = [ 2 "192.168.1.1/24", # Range: 3232235776 - 3232236031 3 "192.168.1.100/24", # Same range 4 "192.168.2.1/24", # 3232236032 - 3232236287 5 "192.168.0.1/16" # 3232235520 - 3232301055 (covers all above) 6]

After converting and merging the ranges:

1output = [ 2 ["192.168.1.1/24", "192.168.1.100/24", "192.168.2.1/24", "192.168.0.1/16"] 3]

Example 2: Disconnected groups

1input = [ 2 "10.0.0.1/24", # 167772160 - 167772415 3 "10.0.0.2/24", # Same 4 "192.168.1.1/24", # 3232235776 - 3232236031 5 "172.16.0.1/16" # 2886729728 - 2886795263 6]

These are separate and non-overlapping ranges, so they form separate groups:

1output = [ 2 ["10.0.0.1/24", "10.0.0.2/24"], 3 ["192.168.1.1/24"], 4 ["172.16.0.1/16"] 5]


Comments