Validate IP Address LeetCode Solution

Last updated on October 5th, 2024 at 08:54 pm

Here, We see Validate IP Address LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

String

Companies

Twitter

Level of Question

Medium

Validate IP Address LeetCode Solution

Validate IP Address LeetCode Solution

Problem Statement

Given a string queryIP, return “IPv4” if IP is a valid IPv4 address, “IPv6” if IP is a valid IPv6 address or “Neither” if IP is not a correct IP of any type.

A valid IPv4 address is an IP in the form “x1.x2.x3.x4” where 0 <= xi <= 255 and xi cannot contain leading zeros. For example, “192.168.1.1” and “192.168.1.0” are valid IPv4 addresses while “192.168.01.1”, “192.168.1.00”, and “192.168@1.1” are invalid IPv4 addresses.

A valid IPv6 address is an IP in the form “x1😡2😡3😡4😡5😡6😡7😡8” where:

  • 1 <= xi.length <= 4
  • xi is a hexadecimal string which may contain digits, lowercase English letter (‘a’ to ‘f’) and upper-case English letters (‘A’ to ‘F’).
  • Leading zeros are allowed in xi.

For example, “2001:0db8:85a3:0000:0000:8a2e:0370:7334” and “2001:db8:85a3:0:0:8A2E:0370:7334” are valid IPv6 addresses, while “2001:0db8:85a3::8A2E:037j:7334” and “02001:0db8:85a3:0000:0000:8a2e:0370:7334” are invalid IPv6 addresses.

Example 1:
Input: queryIP = “172.16.254.1”
Output: “IPv4”
Explanation: This is a valid IPv4 address, return “IPv4”.

Example 2:
Input: queryIP = “2001:0db8:85a3:0:0:8A2E:0370:7334”
Output: “IPv6”
Explanation: This is a valid IPv6 address, return “IPv6”.

Example 3:
Input: queryIP = “256.256.256.256”
Output: “Neither”
Explanation: This is neither a IPv4 address nor a IPv6 address.

1. Validate IP Address LeetCode Solution C++

class Solution {
public:
    string validIPAddress(string queryIP) {
        regex ipv4("(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"), ipv6("((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}");
        if(regex_match(queryIP, ipv4))
            return "IPv4";
        else if(regex_match(queryIP, ipv6))
            return "IPv6";
        return "Neither";      
    }
};

2. Validate IP Address LeetCode Solution Java

class Solution {
    public String validIPAddress(String queryIP) {
        if(queryIP.length()==0) return "Neither";
        if(queryIP.indexOf(".")&gt;=0) return validateIPV4(queryIP);
        if(queryIP.indexOf(":")&gt;=0) return validateIPV6(queryIP);
        return "Neither";
    }
    private  String validateIPV4(String ip){
        if(ip.charAt(0)=='.' || ip.charAt(ip.length()-1)=='.') return "Neither";
          String[] component=ip.split("\\.");
           if(component.length!=4) return "Neither";
           for(String comp:component){
             if(comp.length()==0 || comp.length()&gt;3 || (comp.charAt(0)=='0' &amp;&amp; comp.length()&gt;1)){
                 return "Neither";
             }
              for(char ch:comp.toCharArray()){
                  if(ch&lt;'0' || ch&gt;'9') return "Neither";
              }
              int num=Integer.parseInt(comp);
              if(num&lt;0 || num&gt;255) return "Neither";
           }
           return "IPv4";
           }
   private String validateIPV6(String ip){
     if(ip.charAt(0)==':' || ip.charAt(ip.length()-1)==':') return "Neither";
       String[] component=ip.split(":");
       if(component.length!=8) return "Neither";
       for(String comp:component){
       if(comp.length()==0 || comp.length()&gt;4) return "Neither";
           for(char ch:comp.toLowerCase().toCharArray()){
             if((ch&lt;'0' || ch&gt;'9') &amp;&amp; (ch!='a' &amp;&amp; ch!='b' &amp;&amp; ch!='c' &amp;&amp; ch!='d' &amp;&amp; ch!='e' &amp;&amp; ch!='f')){
                 return "Neither";
             }  
           }
       }
       return "IPv6";
     }
 }

3. Validate IP Address Solution JavaScript

var validIPAddress = function(queryIP) {
    const ipv4 = /^((\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.){4}$/;
    const ipv6 = /^([\da-f]{1,4}:){8}$/i;
    return ipv4.test(queryIP + '.') ? 'IPv4' : ipv6.test(queryIP + ':') ? 'IPv6' : 'Neither';    
};

4. Validate IP Address Solution Python

class Solution(object):
    def validIPAddress(self, queryIP):
        res = 0
        ipv4 = queryIP.split('.')
        if len(ipv4) == 4:
            for x in ipv4:
                if x == '' or (x[0] == '0' and len(x) != 1) or not x.isdigit() or int(x) &gt; 255:
                    res = 1
                    break
            if not res:
                return 'IPv4'
        ipv6 = queryIP.split(':')
        if len(ipv6) == 8:
            for x in ipv6:
                if x == '' or len(x) &gt; 4 or not all(c in hexdigits for c in x):
                    res = 1
                    break
            if not res:
                return 'IPv6'
        return 'Neither'
Scroll to Top