Given a string s in the form of an IPv4 Address. The 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 <= (x1, x2, x3, x4) <= 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: s = "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: s = "5555..555"
Output: false
Explanation: "5555..555" is not a valid IPv4 address, as the middle two portions are missing.Input: s = "0.0.0.255"
Output: true
Table of Content
[Naive Approach] Inbuilt Library Methods - O(n) Time and O(n) Space
We use built-in methods to split the IP address into sections using . . Then, each section is checked to ensure it is valid and its value lies within the range 0-255.
- If all sections are valid, return true.
- If any section is invalid, return false.
#include <bits/stdc++.h>
using namespace std;
int isValid(string &s)
{
int n = s.size();
if (n < 7)
return false;
// Using string stream to separate all
// the string from '.' and push back
// into vector
vector<string> v;
stringstream ss(s);
while (ss.good())
{
string substr;
getline(ss, substr, '.');
v.push_back(substr);
}
if (v.size() != 4)
return false;
// Iterating over the generated vector of strings
for (int i = 0; i < v.size(); i++)
{
string temp = v[i];
// Empty section is invalid
if (temp.empty())
return false;
if (temp.size() > 1)
{
if (temp[0] == '0')
return false;
}
for (int j = 0; j < temp.size(); j++)
{
if (isalpha(temp[j]))
return false;
}
// Check if the number is greater than 255
if (stoi(temp) > 255)
return false;
}
return true;
}
int main()
{
string s = "222.111.111.111";
isValid(s) ? cout << "true" : cout << "false";
return 0;
}
import java.util.ArrayList;
import java.util.StringTokenizer;
public class GFG {
public static boolean isValid(String s)
{
int n = s.length();
if (n < 7)
return false;
// Using string tokenizer to separate all
// the string from '.' and push back
// into ArrayList
ArrayList<String> v = new ArrayList<>();
StringTokenizer st = new StringTokenizer(s, ".");
while (st.hasMoreTokens()) {
v.add(st.nextToken());
}
if (v.size() != 4)
return false;
// Iterating over the generated ArrayList of strings
for (int i = 0; i < v.size(); i++) {
String temp = v.get(i);
// Empty section is invalid
if (temp.isEmpty())
return false;
if (temp.length() > 1) {
if (temp.charAt(0) == '0')
return false;
}
for (int j = 0; j < temp.length(); j++) {
if (Character.isAlphabetic(temp.charAt(j)))
return false;
}
// Check if the number is greater than 255
if (Integer.parseInt(temp) > 255)
return false;
}
return true;
}
public static void main(String[] args)
{
String s = "222.111.111.111";
System.out.println(isValid(s) ? "true" : "false");
}
}
def isValid(s):
n = len(s)
if n < 7:
return False
# Using split to separate all
# the string from '.' and push back
# into list
v = s.split('.')
if len(v) != 4:
return False
# Iterating over the generated list of strings
for i in range(len(v)):
temp = v[i]
# Empty section is invalid
if len(temp) == 0:
return False
if len(temp) > 1:
if temp[0] == '0':
return False
for j in range(len(temp)):
if temp[j].isalpha():
return False
# Check if the number is greater than 255
if int(temp) > 255:
return False
return True
if __name__ == '__main__':
s = "222.111.111.111"
print('true' if isValid(s) else 'false')
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG {
public static bool isValid(string s)
{
int n = s.Length;
if (n < 7)
return false;
// Using split to separate all
// the string from '.' and push back
// into list
List<string> v = s.Split('.').ToList();
if (v.Count != 4)
return false;
// Iterating over the generated list of strings
for (int i = 0; i < v.Count; i++) {
string temp = v[i];
// Empty section is invalid
if (string.IsNullOrEmpty(temp))
return false;
if (temp.Length > 1) {
if (temp[0] == '0')
return false;
}
for (int j = 0; j < temp.Length; j++) {
if (char.IsLetter(temp[j]))
return false;
}
// Check if the number is greater than 255
if (int.Parse(temp) > 255)
return false;
}
return true;
}
public static void Main()
{
string s = "222.111.111.111";
Console.WriteLine(isValid(s) ? "true" : "false");
}
}
function isValid(s)
{
let n = s.length;
if (n < 7)
return false;
// Using split to separate all
// the string from '.' and push back
// into array
let v = s.split(".");
if (v.length != 4)
return false;
// Iterating over the generated array of strings
for (let i = 0; i < v.length; i++) {
let temp = v[i];
// Empty section is invalid
if (temp.length === 0)
return false;
if (temp.length > 1) {
if (temp[0] === "0")
return false;
}
for (let j = 0; j < temp.length; j++) {
if (/[a-zA-Z]/.test(temp[j]))
return false;
}
// Check if the number is greater than 255
if (parseInt(temp) > 255)
return false;
}
return true;
}
// Driver Code
let s = "222.111.111.111";
console.log(isValid(s) ? "true" : "false");
Output
true
[Expected Approach] Validating Each IP Section Using String Traversal - O(n) Time and O(1) Space
We traverse the IP address section by section and check each section for valid digits, length, leading zeros, and a value between 0 and 255.
- If any section fails these conditions, return false.
- If all sections are valid and there are exactly 4 sections, return true.
Let us understand with an example:
Input: s = "222.111.111.111"
- The string is split into four parts: "222", "111", "111", and "111".
- Each part contains only digits, has at most 3 digits, and has no leading zero.
- The values 222, 111, 111, and 111 all lie between 0 and 255.
- segmentCount becomes 4 after processing all four parts.
- Since all parts are valid and segmentCount == 4, the function returns true.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
// Function to check if a part of the IPv4 address is valid
bool valid_part(string &s)
{
int n = s.length();
// Length must be between 1 and 3
if (n == 0 || n > 3)
return false;
// Check if all characters are digits
for (char c : s)
{
if (c < '0' || c > '9')
return false;
}
// Prevent numbers like "00", "01"
if (s[0] == '0' && n > 1)
return false;
// Convert the part to an integer manually
int num = 0;
for (char c : s)
{
num = num * 10 + (c - '0');
}
// Check if the value lies in the range 0 to 255
return num >= 0 && num <= 255;
}
// Function to check if a given string is a valid IPv4 address
int isValid(string &s)
{
istringstream ss(s);
string part;
int segmentCount = 0;
// Extract each segment separated by '.'
while (getline(ss, part, '.'))
{
// If any segment is invalid, return false
if (!valid_part(part))
return false;
segmentCount++;
}
// A valid IPv4 address must contain exactly 4 segments
return segmentCount == 4;
}
int main()
{
string s = "222.111.111.111";
cout << (isValid(s) ? "true" : "false");
return 0;
}
import java.util.StringTokenizer;
public class GFG {
// Function to check if a part of the IPv4 address is
// valid
public static boolean valid_part(String s)
{
int n = s.length();
// Length must be between 1 and 3
if (n == 0 || n > 3)
return false;
// Check if all characters are digits
for (char c : s.toCharArray()) {
if (c < '0' || c > '9')
return false;
}
// Prevent numbers like "00", "01"
if (s.charAt(0) == '0' && n > 1)
return false;
// Convert the part to an integer manually
int num = 0;
for (char c : s.toCharArray()) {
num = num * 10 + (c - '0');
}
// Check if the value lies in the range 0 to 255
return num >= 0 && num <= 255;
}
// Function to check if a given string is a valid IPv4
// address
public static boolean isValid(String s)
{
StringTokenizer ss = new StringTokenizer(s, ".");
int segmentCount = 0;
// Extract each segment separated by '.'
while (ss.hasMoreTokens()) {
String part = ss.nextToken();
// If any segment is invalid, return false
if (!valid_part(part))
return false;
segmentCount++;
}
// A valid IPv4 address must contain exactly 4
// segments
return segmentCount == 4;
}
public static void main(String[] args)
{
String s = "222.111.111.111";
System.out.println(isValid(s) ? "true" : "false");
}
}
def valid_part(s):
n = len(s)
# Length must be between 1 and 3
if n == 0 or n > 3:
return False
# Check if all characters are digits
for c in s:
if c < '0' or c > '9':
return False
# Prevent numbers like "00", "01"
if s[0] == '0' and n > 1:
return False
# Convert the part to an integer manually
num = 0
for c in s:
num = num * 10 + (ord(c) - ord('0'))
# Check if the value lies in the range 0 to 255
return num >= 0 and num <= 255
def isValid(s):
parts = s.split('.')
segmentCount = 0
# Check each segment of the IP address
for part in parts:
if not valid_part(part):
return False
segmentCount += 1
# A valid IPv4 address must contain exactly 4 segments
return segmentCount == 4
if __name__ == "__main__":
s = "222.111.111.111"
print("true" if isValid(s) else "false")
using System;
public class GFG {
// Function to check if a part of the IPv4 address is
// valid
public static bool valid_part(string s)
{
int n = s.Length;
// Length must be between 1 and 3
if (n == 0 || n > 3)
return false;
// Check if all characters are digits
foreach(char c in s)
{
if (c < '0' || c > '9')
return false;
}
// Prevent numbers like "00", "01"
if (s[0] == '0' && n > 1)
return false;
// Convert the part to an integer manually
int num = 0;
foreach(char c in s) { num = num * 10 + (c - '0'); }
// Check if the value lies in the range 0 to 255
return num >= 0 && num <= 255;
}
// Function to check if a given string is a valid IPv4
// address
public static bool isValid(string s)
{
string[] parts = s.Split('.');
int segmentCount = 0;
// Extract each segment separated by '.'
foreach(string part in parts)
{
// If any segment is invalid, return false
if (!valid_part(part))
return false;
segmentCount++;
}
// A valid IPv4 address must contain exactly 4
// segments
return segmentCount == 4;
}
public static void Main()
{
string s = "222.111.111.111";
Console.WriteLine(isValid(s) ? "true" : "false");
}
}
// Function to check if a part of the IPv4 address is valid
function valid_part(s)
{
let n = s.length;
// Length must be between 1 and 3
if (n === 0 || n > 3) {
return false;
}
// Check if all characters are digits
for (let c of s) {
if (c < "0" || c > "9") {
return false;
}
}
// Prevent numbers like "00", "01"
if (s[0] === "0" && n > 1) {
return false;
}
// Convert the part to an integer manually
let num = 0;
for (let c of s) {
num = num * 10
+ (c.charCodeAt(0) - "0".charCodeAt(0));
}
// Check if the value lies in the range 0 to 255
return num >= 0 && num <= 255;
}
// Function to check if a given string is a valid IPv4
// address
function isValid(s)
{
let parts = s.split(".");
let segmentCount = 0;
// Extract each segment separated by '.'
for (let part of parts) {
// If any segment is invalid, return false
if (!valid_part(part)) {
return false;
}
segmentCount++;
}
// A valid IPv4 address must contain exactly 4 segments
return segmentCount === 4;
}
// Driver Code
let s = "222.111.111.111";
console.log(isValid(s) ? "true" : "false");
Output
true