Validate IP address
Approach:
- Split on the basis of . and make sure we have 4 elements.
- Check if the splits are in the range 0-255. (2^8 = 258)octal
- Null check for every split, if any split is empty or Not A Number then return false.
Time complexity : O(n)
Auxiliary Space : O(1)
NOTE: Some places a leading zero is getting considered for every split, I don’t think it is required as this point of time because “127.0.0.1” won’t match the case.
function isValidIP(ip){
ip=ip.split('.');
if(ip.length!=4) return false
for(let i=0;i<ip.length;i++){
if(ip[i]=='') return false
if(ip[i]<0 || ip[i]>255) return false
if(ip[i].charAt(0)=='0' && ip[i].length>1) return false
}
return true;
}
console.log(isValidIP("1.2.3.4"));
console.log(isValidIP("1.2.3"));
console.log(isValidIP("1.2.3.4.5"));
console.log(isValidIP("123.45.67.89"));
console.log(isValidIP("123.456.78.90"));
console.log(isValidIP("123.045.067.089"));def in_range(n): #check if every split is in range 0-255
if n >= 0 and n<=255:
return True
return False
def has_leading_zero(n): # check if every split has leading zero or not.
if len(n)>1:
if n[0] == "0":
return True
return False
def isValid(s):
s = s.split(".")
if len(s) != 4: #if number of splitting element is not 4 it is not a valid ip address
return 0
for n in s:
if has_leading_zero(n):
return 0
if len(n) == 0:
return 0
try: #if int(n) is not an integer it raises an error
n = int(n)
if not in_range(n):
return 0
except:
return 0
return 1
if __name__=="__main__":
ip1 = "222.111.111.111"
ip2 = "5555..555"
ip3 = "0000.0000.0000.0000"
ip4 = "1.1.1.1"
print(isValid(ip1))
print(isValid(ip2))
print(isValid(ip3))
print(isValid(ip4))
# this code is contributed by Vivek Maddeshiya.
Smallest substring of all chars
Did below code work?

Time complexity: O(N+M) Space complexity: O(M)