We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Validate IP Address

Number: 468

Difficulty: Medium

Paid? No

Companies: Microsoft, Turing, Meta, Amazon, Oracle, TikTok, Apple, Sprinklr, ServiceNow, Nvidia, Deutsche Bank, X


Problem Description

Given a string queryIP, determine whether it is a valid IPv4 address, IPv6 address, or neither. An IPv4 address is in the form x1.x2.x3.x4 where each xi is a decimal number between 0 and 255 without leading zeros (except for the number 0). An IPv6 address is in the form x1:x2:x3:x4:x5:x6:x7:x8 where every xi is a hexadecimal string of 1 to 4 characters (leading zeros are allowed). Return "IPv4" if the input is a valid IPv4 address, "IPv6" if it is a valid IPv6 address, or "Neither" otherwise.


Key Insights

  • Check if the input contains '.' to verify it might be IPv4, or ':' to indicate it may be IPv6.
  • For IPv4:
    • Split the string by '.' and ensure there are exactly 4 components.
    • Each component must be a non-empty string representing an integer in the range [0, 255].
    • No component should have leading zeros unless the number is exactly "0".
  • For IPv6:
    • Split the string by ':' and ensure there are exactly 8 components.
    • Each component must be a non-empty string with length between 1 and 4.
    • Each character in a component must be a valid hexadecimal digit (0-9, a-f, A-F).
  • Edge cases such as extra separators or invalid characters should result in "Neither".

Space and Time Complexity

Time Complexity: O(n) where n is the length of the input string (we process each character at most once)
Space Complexity: O(n) due to the split arrays used for processing the segments


Solution

The solution first determines whether the input is likely IPv4 or IPv6 by looking for '.' or ':'. Depending on the delimiter found, the string is split into segments which are then validated according to the rules for each IP type. For IPv4, each segment must represent an integer between 0 and 255 and must not contain leading zeros (unless it is exactly "0"). For IPv6, each segment must be 1 to 4 characters long and contain only valid hexadecimal characters. If the corresponding criteria for either IP version are not met, we return "Neither".


Code Solutions

def validIPAddress(queryIP):
    # Check if the IP address is IPv4.
    if queryIP.count('.') == 3:
        parts = queryIP.split('.')
        # Validate there are exactly 4 segments.
        if len(parts) != 4:
            return "Neither"
        for part in parts:
            # Each part must be non-empty and numeric.
            if not part or (part[0] == '0' and len(part) != 1) or not part.isdigit():
                return "Neither"
            num = int(part)
            # Check the numeric range for IPv4.
            if not (0 <= num <= 255):
                return "Neither"
        return "IPv4"
    
    # Check if the IP address is IPv6.
    elif queryIP.count(':') == 7:
        parts = queryIP.split(':')
        if len(parts) != 8:
            return "Neither"
        valid_hex = "0123456789abcdefABCDEF"
        for part in parts:
            # Each part must be between 1 and 4 characters.
            if len(part) == 0 or len(part) > 4:
                return "Neither"
            # Each character must be a valid hexadecimal digit.
            for ch in part:
                if ch not in valid_hex:
                    return "Neither"
        return "IPv6"
    
    # If neither condition is met.
    else:
        return "Neither"


# Example test cases
print(validIPAddress("172.16.254.1"))          # Expected output: "IPv4"
print(validIPAddress("2001:0db8:85a3:0:0:8A2E:0370:7334"))  # Expected output: "IPv6"
print(validIPAddress("256.256.256.256"))         # Expected output: "Neither"
← Back to All Questions