Merged IP view
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:
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:
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]