KatInterview

752. IP to CIDR

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the minimum number of CIDR blocks to cover a contiguous range of n IP addresses starting from a given ip. The coverage must be exact, meaning no IPs outside the range [ip, ip + n - 1] should be included.

Solution

IP to CIDR in Python

class Solution:
    def ipToCIDR(self, ip: str, n: int) -> List[str]:
        def ip_to_int(ip_str: str) -> int:
            parts = ip_str.split('.')
            val = 0
            for part in parts:
                val = val * 256 + int(part)
            return val

        def int_to_ip(val: int) -> str:
            parts = []
            for _ in range(4):
                parts.append(str(val & 255))
                val >>= 8
            return ".".join(reversed(parts))

        start_ip = ip_to_int(ip)
        res = []

        while n > 0:
            # Calculate the number of trailing zeros for the current IP.
            # This determines the largest power of 2 that divides start_ip,
            # which in turn limits the size of the CIDR block starting at this IP.
            if start_ip == 0:
                tz = 32
            else:
                # (x & -x) isolates the lowest set bit. Its log2 is the number of trailing zeros.
                tz = (start_ip & -start_ip).bit_length() - 1
            
            # Calculate floor(log2(n)). This helps determine the largest power-of-2
            # block size that is less than or equal to n.
            len_n = n.bit_length() - 1

            # To form a valid CIDR, the prefix length must be at least 32 - tz.
            prefix_from_ip = 32 - tz
            # To not overshoot n, the prefix must be at least 32 - len_n.
            prefix_from_n = 32 - len_n

            # We take the maximum of the two required prefixes to satisfy both conditions.
            # A larger prefix means a smaller block.
            prefix = max(prefix_from_ip, prefix_from_n)

            res.append(f"{int_to_ip(start_ip)}/{prefix}")
            
            # Calculate the number of IPs covered by this CIDR block.
            step = 1 << (32 - prefix)

            # Move to the next IP range to cover.
            start_ip += step
            n -= step
            
        return res

IP to CIDR in Java

class Solution {
    public List<String> ipToCIDR(String ip, int n) {
        long startIp = ipToLong(ip);
        List<String> result = new ArrayList<>();

        while (n > 0) {
            // Calculate the number of trailing zeros for the current IP.
            // If startIp is 0, it has 32 trailing zeros.
            int tz = (startIp == 0) ? 32 : Long.numberOfTrailingZeros(startIp);

            // Calculate floor(log2(n)). This helps determine the largest power-of-2
            // block size that is less than or equal to n.
            // Integer.numberOfLeadingZeros(n) counts leading zeros for a 32-bit integer.
            int len_n = (n == 1) ? 0 : 31 - Integer.numberOfLeadingZeros(n);

            // To form a valid CIDR, the prefix length must be at least 32 - tz.
            int prefix_from_ip = 32 - tz;
            // To not overshoot n, the prefix must be at least 32 - len_n.
            int prefix_from_n = 32 - len_n;

            // We take the maximum of the two required prefixes to satisfy both conditions.
            // A larger prefix means a smaller block.
            int prefix = Math.max(prefix_from_ip, prefix_from_n);

            result.add(longToIp(startIp) + "/" + prefix);

            // Calculate the number of IPs covered by this CIDR block.
            long step = 1L << (32 - prefix);

            // Move to the next IP range to cover.
            startIp += step;
            n -= step;
        }
        return result;
    }

    // Converts an IP string like "a.b.c.d" to its 32-bit integer representation.
    private long ipToLong(String ip) {
        String[] parts = ip.split("\\.");
        long res = 0;
        for (String part : parts) {
            res = res * 256 + Long.parseLong(part);
        }
        return res;
    }

    // Converts a 32-bit integer representation back to an IP string.
    private String longToIp(long val) {
        return ((val >> 24) & 255) + "." +
               ((val >> 16) & 255) + "." +
               ((val >> 8) & 255) + "." +
               (val & 255);
    }
}

IP to CIDR in C++

class Solution {
public:
    vector<string> ipToCIDR(string ip, int n) {
        long long start_ip = ipToLong(ip);
        vector<string> result;

        while (n > 0) {
            // Calculate the number of trailing zeros for the current IP.
            // This determines the largest power of 2 that divides start_ip,
            // which in turn limits the size of the CIDR block starting at this IP.
            int tz = (start_ip == 0) ? 32 : __builtin_ctzll(start_ip);

            // Calculate floor(log2(n)). This helps determine the largest power-of-2
            // block size that is less than or equal to n.
            // __builtin_clz(n) counts leading zeros for a 32-bit integer.
            int len_n = (n == 1) ? 0 : (31 - __builtin_clz(n));
            
            // To form a valid CIDR, the prefix length must be at least 32 - tz.
            int prefix_from_ip = 32 - tz;
            // To not overshoot n, the prefix must be at least 32 - len_n.
            int prefix_from_n = 32 - len_n;
            
            // We take the maximum of the two required prefixes to satisfy both conditions.
            // A larger prefix means a smaller block.
            int prefix = max(prefix_from_ip, prefix_from_n);
            
            result.push_back(longToIp(start_ip) + "/" + to_string(prefix));
            
            // Calculate the number of IPs covered by this CIDR block.
            long long step = 1LL << (32 - prefix);
            
            // Move to the next IP range to cover.
            start_ip += step;
            n -= step;
        }
        return result;
    }

private:
    // Converts an IP string like "a.b.c.d" to its 32-bit integer representation.
    long long ipToLong(const string& ip) {
        unsigned int p1, p2, p3, p4;
        char dot;
        stringstream ss(ip);
        ss >> p1 >> dot >> p2 >> dot >> p3 >> dot >> p4;
        return (static_cast<long long>(p1) << 24) |
               (static_cast<long long>(p2) << 16) |
               (static_cast<long long>(p3) << 8)  |
               (static_cast<long long>(p4));
    }
    
    // Converts a 32-bit integer representation back to an IP string.
    string longToIp(long long val) {
        string ip_str;
        ip_str += to_string((val >> 24) & 255);
        ip_str += ".";
        ip_str += to_string((val >> 16) & 255);
        ip_str += ".";
        ip_str += to_string((val >> 8) & 255);
        ip_str += ".";
        ip_str += to_string(val & 255);
        return ip_str;
    }
};

IP to CIDR in TypeScript

function ipToCIDR(ip: string, n: number): string[] {
    const ipToLong = (ipStr: string): number => {
        // JavaScript numbers have 53 bits of precision, so a 32-bit unsigned int fits.
        return ipStr.split('.').reduce((acc, part) => (acc * 256) + parseInt(part), 0);
    };

    const longToIp = (val: number): string => {
        // Use unsigned right shift (>>>) to handle 32-bit numbers correctly.
        return `${(val >>> 24)}.${(val >>> 16) & 255}.${(val >>> 8) & 255}.${val & 255}`;
    };

    let startIp = ipToLong(ip);
    const result: string[] = [];

    while (n > 0) {
        // Calculate the number of trailing zeros for the current IP.
        let tz = 0;
        if (startIp === 0) {
            tz = 32;
        } else {
            // Isolate lowest set bit and find its position (which is # of trailing zeros)
            let lsb = startIp & -startIp;
            tz = Math.log2(lsb);
        }

        // Calculate floor(log2(n)).
        const lenN = Math.floor(Math.log2(n));

        // To form a valid CIDR, the prefix must be at least 32 - tz.
        const prefixFromIp = 32 - tz;
        // To not overshoot n, the prefix must be at least 32 - len_n.
        const prefixFromN = 32 - lenN;

        // We take the maximum of the two required prefixes to satisfy both conditions.
        const prefix = Math.max(prefixFromIp, prefixFromN);

        result.push(`${longToIp(startIp)}/${prefix}`);

        // Calculate the number of IPs covered by this CIDR block.
        const step = 1 << (32 - prefix);

        // Move to the next IP range to cover.
        startIp += step;
        n -= step;
    }

    return result;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.