https://leetcode.com/problems/validate-ip-address

The main difficulty of this problem if you meet it on real interview, is to not forget any border cases, there are a lot of them. First of all let us split problem into two subproblems: possible candidates for IPv4 and possible candidates for IPv6.

  1. We have candidate for IPv4 if we meet symbol . in our data. If we met it, we split our data into parts, using . and we need to check: 1.1 If we have not 4 parts, we return "Neither". 1.2 We check each part and if it is empty and if it starts with zero, but not zero, we also return "Neither". 1.3 Finally, we check that every part is number and is less than 256, if it is not true, we return "Neither". 1.4 If we passed all previous steps, we return IPv4.
  2. We have candidate for IPv4 if we meet symbol : in our data. If we met it, we split our data into parts, using : and we need to check: 2.1 If number of parts not equal to 8, we return "Neither" 2.2 If we have empty parts of parts with length more than 4, we return "Neither" 2.3 We check each symbol in our part and if we found something not in 1234567890abcdefABCDEF, we return "Neither" 2.4 If we passed all previous steps, we return IPv6.

Complexity: both time and space are O(n), where n is number of elements in our string.

class Solution:
    def validIPAddress(self, IP):
        if "." in IP:
            splitted = IP.split(".")
            if len(splitted) != 4: return "Neither"
            for part in splitted:
                if len(part) == 0 or (len(part)>1 and part[0] == "0"): return "Neither"
                if not part.isnumeric() or int(part) > 255: return "Neither"                
            return "IPv4"        
        elif ":" in IP:
            symbols = "0123456789abcdefABCDEF"
            splitted = IP.split(":")
            if len(splitted) != 8: return "Neither"
            for part in splitted:
                if len(part) == 0 or len(part) > 4: return "Neither"
                for elem in part:
                    if elem not in symbols: return "Neither"                 
            return "IPv6"      
        return "Neither"

If you like the solution, you can upvote it on leetcode discussion section: Problem 0468