KatInterview

468. Validate IP Address

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 validate if a given string queryIP is a valid IPv4 address, a valid IPv6 address, or neither. The rules for both types of addresses are very specific and strict.

Solution

Validate IP Address in Python

class Solution:
    def validIPAddress(self, queryIP: str) -> str:
        # First, categorize by counting delimiters.
        if queryIP.count('.') == 3:
            # Potential IPv4
            parts = queryIP.split('.')
            # If split results in a number of parts different than 4, it's invalid.
            # This catches cases like '1.2.3.4.' or '..1.2.3'
            if len(parts) != 4:
                return "Neither"
            
            for part in parts:
                # Each part must be digits.
                if not part.isdecimal():
                    return "Neither"
                
                # Check for leading zeros: '0' is valid, but '01' is not.
                if len(part) > 1 and part.startswith('0'):
                    return "Neither"
                
                # Value must be between 0 and 255.
                if not (0 <= int(part) <= 255):
                    return "Neither"
            
            return "IPv4"
        
        elif queryIP.count(':') == 7:
            # Potential IPv6
            parts = queryIP.split(':')
            # This catches cases like '2001::...' or '...:7334:'
            if len(parts) != 8:
                return "Neither"

            valid_hex_chars = "0123456789abcdefABCDEF"
            for part in parts:
                # Length must be between 1 and 4.
                if not (1 <= len(part) <= 4):
                    return "Neither"
                
                # All characters must be hex digits.
                if not all(c in valid_hex_chars for c in part):
                    return "Neither"
            
            return "IPv6"
        
        # If neither of the above, it's not a valid IP.
        return "Neither"

Validate IP Address in Java

class Solution {
    public String validIPAddress(String queryIP) {
        // Count delimiters to quickly categorize.
        long dotCount = queryIP.chars().filter(ch -> ch == '.').count();
        long colonCount = queryIP.chars().filter(ch -> ch == ':').count();

        if (dotCount == 3 && colonCount == 0) {
            // Use split with limit -1 to include trailing empty strings.
            String[] parts = queryIP.split("\\.", -1);
            if (parts.length != 4) {
                return "Neither";
            }
            for (String part : parts) {
                if (part.isEmpty() || part.length() > 3) {
                    return "Neither";
                }
                // Check for leading zeros
                if (part.length() > 1 && part.charAt(0) == '0') {
                    return "Neither";
                }
                // Check if all characters are digits
                for (char c : part.toCharArray()) {
                    if (!Character.isDigit(c)) {
                        return "Neither";
                    }
                }
                // Check range
                try {
                    if (Integer.parseInt(part) > 255) {
                        return "Neither";
                    }
                } catch (NumberFormatException e) {
                    // This case should be covered by isDigit checks, but good for safety.
                    return "Neither";
                }
            }
            return "IPv4";
        } else if (colonCount == 7 && dotCount == 0) {
            String[] parts = queryIP.split(":", -1);
            if (parts.length != 8) {
                return "Neither";
            }
            for (String part : parts) {
                if (part.isEmpty() || part.length() > 4) {
                    return "Neither";
                }
                // Check for valid hex characters
                for (char c : part.toCharArray()) {
                    if (!Character.isDigit(c) && (Character.toLowerCase(c) < 'a' || Character.toLowerCase(c) > 'f')) {
                        return "Neither";
                    }
                }
            }
            return "IPv6";
        }

        return "Neither";
    }
}

Validate IP Address in C++

class Solution {
public:
    string validIPAddress(string queryIP) {
        if (count(queryIP.begin(), queryIP.end(), '.') == 3) {
            return validateIPv4(queryIP);
        } else if (count(queryIP.begin(), queryIP.end(), ':') == 7) {
            return validateIPv6(queryIP);
        }
        return "Neither";
    }

private:
    string validateIPv4(const string& ip) {
        // stringstream is one way to split, but manual splitting is also clear.
        // Let's use stringstream.
        stringstream ss(ip);
        string part;
        int part_count = 0;

        // The last character cannot be a dot.
        if (ip.back() == '.') {
            return "Neither";
        }

        while (getline(ss, part, '.')) {
            part_count++;
            // Check part properties
            if (part.empty() || part.length() > 3) {
                return "Neither";
            }
            if (part.length() > 1 && part[0] == '0') {
                return "Neither";
            }
            for (char c : part) {
                if (!isdigit(c)) {
                    return "Neither";
                }
            }
            if (stoi(part) > 255) {
                return "Neither";
            }
        }
        
        // Ensure we have exactly 4 parts.
        if (part_count != 4) {
            return "Neither";
        }

        return "IPv4";
    }

    string validateIPv6(const string& ip) {
        stringstream ss(ip);
        string part;
        int part_count = 0;

        // The last character cannot be a colon.
        if (ip.back() == ':') {
            return "Neither";
        }

        while (getline(ss, part, ':')) {
            part_count++;
            // Check part properties
            if (part.empty() || part.length() > 4) {
                return "Neither";
            }
            for (char c : part) {
                if (!isxdigit(c)) {
                    return "Neither";
                }
            }
        }

        // Ensure we have exactly 8 parts.
        if (part_count != 8) {
            return "Neither";
        }

        return "IPv6";
    }
};

Validate IP Address in TypeScript

function validIPAddress(queryIP: string): string {
    const checkIPv4 = (ip: string): boolean => {
        const parts = ip.split('.');
        if (parts.length !== 4) {
            return false;
        }

        for (const part of parts) {
            // Check for empty part
            if (part.length === 0) {
                return false;
            }
            // Check for non-digit characters
            if (!/^[0-9]+$/.test(part)) {
                return false;
            }
            // Check for leading zeros
            if (part.length > 1 && part.startsWith('0')) {
                return false;
            }
            // Check range
            const num = parseInt(part, 10);
            if (num < 0 || num > 255) {
                return false;
            }
        }
        return true;
    };

    const checkIPv6 = (ip: string): boolean => {
        const parts = ip.split(':');
        if (parts.length !== 8) {
            return false;
        }

        for (const part of parts) {
            // Check length
            if (part.length < 1 || part.length > 4) {
                return false;
            }
            // Check for invalid hex characters
            if (!/^[0-9a-fA-F]+$/.test(part)) {
                return false;
            }
        }
        return true;
    };

    // Using count of delimiters is a good first-pass check
    const dotCount = queryIP.split('.').length - 1;
    const colonCount = queryIP.split(':').length - 1;

    if (dotCount === 3 && colonCount === 0) {
        if (checkIPv4(queryIP)) {
            return "IPv4";
        }
    } else if (colonCount === 7 && dotCount === 0) {
        if (checkIPv6(queryIP)) {
            return "IPv6";
        }
    }

    return "Neither";
}

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.