Validate an IP Address | Problem of the Day | GeeksForGeeks
You are given a string str in the form of an IPv4 Address. Your task is to validate an IPv4 Address, if it is valid return true otherwise return false.
IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots, e.g., 172.16.254.1
A valid IPv4 Address is of the form x1.x2.x3.x4 where 0 less than or equal to (x1, x2, x3, x4) less than or equal to 255. Thus, we can write the generalized form of an IPv4 address as (0-255).(0-255).(0-255).(0-255)
Note: Here we are considering numbers only from 0 to 255 and any additional leading zeroes will be considered invalid.
Examples :
Input: str = 222.111.111.111
Output: true
Explanation: Here, the IPv4 address is as per the criteria mentioned and also all four decimal numbers lies in the mentioned range.
Input: str = 5555..555
Output: false
Explanation: 5555..555 is not a valid. IPv4 address, as the middle two portions are missing.
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)
Table of Contents
0:00 Problem Statement
0:39 Solution
2:37 Pseudo Code
4:32 Code – Python
5:40 Code – C++
ipv4
class Solution:
def isValid(self, str):
ip = str.split(".")
if len(ip) != 4:
return False
for x in ip:
#print(f"{len(x)} and {x[0]}")
if len(x) >= 2 and x[0] == '0':
return False
for element in x:
if not element.isdigit():
return False
int_x = int(x)
if int_x < 0 or int_x > 255:
return False
return True
class Solution {
public:
int valid_part(string sub_str) {
if (sub_str.length() > 3)
return false;
if (sub_str.length() >= 2 and sub_str[0] == '0')
return false;
int x = stoi(sub_str);
//cout <<x<<endl;
if (x < 0 or x > 255)
return false;
return true;
}
int isValid(string str) {
int num_dot = 0;
string sub_str = "";
for (int i = 0; i < str.length(); i++) {
if (str[i] == '.') {
num_dot++;
if (valid_part(sub_str) == false)
return false;
sub_str = "";
}
else {
if (!(str[i] >= '0' and str[i] <= '9'))
return false;
sub_str += str[i];
}
}
if (num_dot != 3)
return false;
if (valid_part(sub_str) == false)
return false;
return true;
}
};
Table of Contents
0:00 Problem Statement
0:39 Solution
2:37 Pseudo Code
4:32 Code – Python
5:40 Code – C++