468. Validate IP Address – Solution [Brute-Force to Best]

Here’s the question link on LeetCode 468. Validate IP Address:-

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

Optimal O(n) String Splitting + Validation

My approach here is pretty straightforward.

We have two different formats, so let’s write two functions:

  • isIPv4() checks whether the string follows IPv4 rules.
  • isIPv6() checks whether the string follows IPv6 rules.

We split the string using the appropriate separator and validate every part.

If neither validation passes, return "Neither".

class Solution {
public:
    bool isIPv4(string s) {
        // A trailing dot means an empty last part
        if(s.empty() || s.back() == '.')
            return false;

        stringstream ss(s);
        string part;
        int count = 0;

        while(getline(ss, part, '.')) {
            count++;

            if(part.empty() || part.size() > 3)
                return false;

            // No leading zeros
            if(part.size() > 1 && part[0] == '0')
                return false;

            // Only digits are allowed
            for(char c : part) {
                if(!isdigit(c))
                    return false;
            }

            int num = stoi(part);

            if(num < 0 || num > 255)
                return false;
        }

        return count == 4;
    }

    bool isIPv6(string s) {
        // A trailing colon means an empty last part
        if(s.empty() || s.back() == ':')
            return false;

        stringstream ss(s);
        string part;
        int count = 0;

        string valid = "0123456789abcdefABCDEF";

        while(getline(ss, part, ':')) {
            count++;

            if(part.empty() || part.size() > 4)
                return false;

            // Only hexadecimal characters are allowed
            for(char c : part) {
                if(valid.find(c) == string::npos)
                    return false;
            }
        }

        return count == 8;
    }

    string validIPAddress(string queryIP) {
        if(queryIP.find('.') != string::npos) {
            if(isIPv4(queryIP))
                return "IPv4";
        }

        if(queryIP.find(':') != string::npos) {
            if(isIPv6(queryIP))
                return "IPv6";
        }

        return "Neither";
    }
};
468. Validate IP Address Optimal solution

Leave a Reply