Validate IP Address - Solution & Explanation
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:x2:x3:x4:x5:x6:x7:x8" where:
1 <= xi.length <= 4xiis 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.
Constraints:
queryIPconsists only of English letters, digits and the characters'.'and':'.
Approach Overview
Problem Overview: Given a string queryIP, determine whether it represents a valid IPv4 address, a valid IPv6 address, or neither. The validation rules differ for each format: IPv4 contains four decimal numbers separated by dots, while IPv6 contains eight hexadecimal groups separated by colons.
Approach 1: Split and Validate (O(n) time, O(1) space)
This approach parses the input string using delimiter-based splitting. First check whether the string contains '.' or ':'. For IPv4, split by dots and verify exactly four segments. Each segment must contain only digits, cannot have leading zeros unless the value is exactly 0, and must fall within the range 0–255. For IPv6, split by colons and verify exactly eight segments. Each segment must contain 1–4 hexadecimal characters (0-9, a-f, A-F). Iterate through each segment and validate character-by-character.
This method works well because the format rules are strict and easy to enforce with simple string checks. Operations include split, length validation, numeric parsing, and character validation. Since the input length is bounded (maximum 39 characters for IPv6), the algorithm runs in linear time relative to the string length. Most interview solutions use this strategy because it clearly demonstrates understanding of string processing and input validation.
Approach 2: Regular Expression Validation (O(n) time, O(1) space)
Another option uses carefully constructed regular expressions to match valid IPv4 and IPv6 formats. One regex pattern enforces IPv4 rules: four numeric groups separated by dots with values restricted to 0–255. Another pattern enforces IPv6 rules: eight groups of 1–4 hexadecimal characters separated by colons. Run the string against both patterns; if the IPv4 pattern matches return "IPv4", if the IPv6 pattern matches return "IPv6", otherwise return "Neither".
Regex compresses the validation logic into a single pattern match. The tradeoff is readability—complex numeric range checks make the expression harder to maintain. Still, regex engines scan the string only once, giving linear time complexity. This method is common in production codebases where regular expression validation already exists.
Recommended for interviews: The split-and-validate approach. It shows clear reasoning about parsing, numeric constraints, and edge cases like leading zeros or invalid hexadecimal characters. Regex demonstrates familiarity with pattern matching but hides the validation logic, so interviewers often prefer the explicit string parsing approach using string operations.
Approach 1: Approach 1: Split and Validate
This approach involves splitting the input string based on separators '.' and ':'. Use these segments to determine whether the input is a valid IPv4 or IPv6 address based on segment counts and content constraints.
The Python solution splits the input string by '.' for IPv4 validation and checks each part for integer validation within [0, 255] without leading zeros. Similarly, it splits by ':' for IPv6 and checks the hexadecimal validity of each segment.
Code
Python
JavaScript
Complexity
Time Complexity: O(N), where N is the length of the input string.
Space Complexity: O(1), aside from the input storage.
Approach 2: Approach 2: Regular Expression Validation
This approach uses regular expressions to directly match the input string against IPv4 and IPv6 patterns. It's a succinct method that can validate the format using concise expressions.
In Java, we can use `Pattern.matches` to compare the IP string against regular expressions representing valid IPv4 and IPv6 formats to determine validity.
Complexity
Time Complexity: O(1), since regular expression matching is handled internally and expected to be near constant-time on average.
Space Complexity: O(1), for storing pattern strings.
Approach 3: Simulation
We can define two functions isIPv4 and isIPv6 to determine whether a string is a valid IPv4 address and IPv6 address.
The implementation of the function isIPv4 is as follows:
- We first check if the string
sends with.. If so,sis not a valid IPv4 address, and we directly returnfalse. - Then we split the string
sby.into a string arrayss. If the length ofssis not4,sis not a valid IPv4 address, and we directly returnfalse. - For each string
tin the arrayss, we check:- If the length of
tis greater than1and the first character oftis0,tis not a valid IPv4 address, and we directly returnfalse. - If
tis not a number ortis not in the range of0to255,tis not a valid IPv4 address, and we directly returnfalse.
- If the length of
- If none of the above conditions are met,
sis a valid IPv4 address, and we returntrue.
The implementation of the function isIPv6 is as follows:
- We first check if the string
sends with:. If so,sis not a valid IPv6 address, and we directly returnfalse. - Then we split the string
sby:into a string arrayss. If the length ofssis not8,sis not a valid IPv6 address, and we directly returnfalse. - For each string
tin the arrayss, we check:- If the length of
tis less than1or greater than4,tis not a valid IPv6 address, and we directly returnfalse. - If the characters in
tare not all between0and9andaandf(case insensitive),tis not a valid IPv6 address, and we directly returnfalse.
- If the length of
- If none of the above conditions are met,
sis a valid IPv6 address, and we returntrue.
Finally, we call the isIPv4 and isIPv6 functions to determine if queryIP is a valid IPv4 address or IPv6 address. If it is neither, we return Neither.
The time complexity is O(n), and the space complexity is O(n). Where n is the length of the string queryIP.
Complexity Comparison
| Approach | Complexity |
|---|---|
| Approach 1: Split and Validate | Time Complexity: O(N), where N is the length of the input string. |
| Approach 2: Regular Expression Validation | Time Complexity: O(1), since regular expression matching is handled internally and expected to be near constant-time on average. |
| Simulation | — |
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Split and Validate | O(n) | O(1) | Best for interviews and readable implementations with explicit validation logic |
| Regular Expression Validation | O(n) | O(1) | When regex libraries are preferred or validation rules need to be enforced with pattern matching |
Video Solution
Validate IP Address | Regex | Leetcode #468 • Techdose • 42,989 views views
Watch 9 more video solutions →Frequently Asked Questions
Is Validate IP Address easy or hard?
How to solve Validate IP Address in O(n)?
What is the best approach for Validate IP Address?
What data structure is used in Validate IP Address?
What is the time complexity of Validate IP Address?
Validate IP Address Python or Java solution approach
Is Validate IP Address asked at Google, Amazon, or Meta?
Ready to solve this problem?
Practice Validate IP Address with our built-in code editor and test cases.
Practice on FleetCode