06(Aug) Validate an IP Address
06. Validate an IP Address
The problem can be found at the following link: Question Link
Problem Description
You are given a string str in the form of an IPv4 address. Your task is to validate the 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:
str = "222.111.111.111"Output:
trueExplanation: The IPv4 address is as per the criteria mentioned, and all four decimal numbers lie in the specified range.
Input:
str = "5555..555"Output:
falseExplanation: "5555..555" is not a valid IPv4 address, as the middle two portions are missing.
My Approach
Initialization:
Define variables
segments,num, andlengthto keep track of the number of segments, the current number, and the length of the current number, respectively.
Validation Loop:
Iterate through each character in the string
str.If the character is a dot (
.):Check if the
lengthis between 1 and 3 and thenumis between 0 and 255.If any of these checks fail, return
false.Increment
segments, resetnum, andlength.
If the character is a digit:
Check if the current segment starts with '0' and is not followed by a dot.
Calculate the new
numand incrementlength.
If the character is neither a dot nor a digit, return
false.
Final Checks:
Ensure the last segment is valid by checking the
lengthandnum.Ensure there are exactly four segments.
Return:
Return
trueif the IP address is valid, otherwisefalse.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we iterate through each character in the string once.
Expected Auxiliary Space Complexity: O(1), as we use a constant amount of additional space.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated