algoadvance

The problem is to write a function that determines whether a given string is a valid IPv4 or IPv6 address or neither.

The output should be:

Clarifying Questions

  1. Input Constraints:
    • Can the input string be empty or contain only white spaces?
    • Should we consider the input to be case-sensitive for IPv6 addresses?
  2. Edge Cases:
    • Should we consider non-standard cases, such as a string with a mixture of IPv4 and IPv6 formats?

Code

def validIPAddress(IP: str) -> str:
    def is_valid_ipv4(ip):
        parts = ip.split(".")
        if len(parts) != 4:
            return False
        for part in parts:
            if not part.isdigit():
                return False
            if len(part) > 1 and part[0] == '0':
                return False
            if not 0 <= int(part) <= 255:
                return False
        return True

    def is_valid_ipv6(ip):
        parts = ip.split(":")
        if len(parts) != 8:
            return False
        hexdigits = '0123456789abcdefABCDEF'
        for part in parts:
            if len(part) == 0 or len(part) > 4:
                return False
            for char in part:
                if char not in hexdigits:
                    return False
        return True

    if IP.count('.') == 3 and is_valid_ipv4(IP):
        return "IPv4"
    elif IP.count(':') == 7 and is_valid_ipv6(IP):
        return "IPv6"
    else:
        return "Neither"

Strategy

  1. IPv4 Validation:
    • Split the IP address by periods (".").
    • Ensure there are exactly four parts.
    • Check each part to ensure it:
      • Contains only digits.
      • Does not have leading zeros (except for the number ‘0’).
      • Falls within the range 0 to 255.
  2. IPv6 Validation:
    • Split the IP address by colons (":").
    • Ensure there are exactly eight parts.
    • Check each part to ensure it:
      • Is not empty and does not exceed four characters in length.
      • Contains only valid hexadecimal characters (0-9, a-f, A-F).

Time Complexity

Both validation methods are constant time operations since the given constraints ensure a fixed number of checks regardless of input size.

Try our interview co-pilot at AlgoAdvance.com