Skip to main content

Validate IP Address - Solution & Explanation

MediumString21 min readAsked at: Amazon, Microsoft, Apple +9
Practice this problem

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 <= 4
  • xi is 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:

  • queryIP consists 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.

Try this approach in the editor →

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.

Code

Java

C#

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.

Try this approach in the editor →

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:

  1. We first check if the string s ends with .. If so, s is not a valid IPv4 address, and we directly return false.
  2. Then we split the string s by . into a string array ss. If the length of ss is not 4, s is not a valid IPv4 address, and we directly return false.
  3. For each string t in the array ss, we check:
    • If the length of t is greater than 1 and the first character of t is 0, t is not a valid IPv4 address, and we directly return false.
    • If t is not a number or t is not in the range of 0 to 255, t is not a valid IPv4 address, and we directly return false.
  4. If none of the above conditions are met, s is a valid IPv4 address, and we return true.

The implementation of the function isIPv6 is as follows:

  1. We first check if the string s ends with :. If so, s is not a valid IPv6 address, and we directly return false.
  2. Then we split the string s by : into a string array ss. If the length of ss is not 8, s is not a valid IPv6 address, and we directly return false.
  3. For each string t in the array ss, we check:
    • If the length of t is less than 1 or greater than 4, t is not a valid IPv6 address, and we directly return false.
    • If the characters in t are not all between 0 and 9 and a and f (case insensitive), t is not a valid IPv6 address, and we directly return false.
  4. If none of the above conditions are met, s is a valid IPv6 address, and we return true.

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.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Approach 1: Split and Validate

Time Complexity: O(N), where N is the length of the input string.
Space Complexity: O(1), aside from the input storage.

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.
Space Complexity: O(1), for storing pattern strings.

Simulation—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Split and ValidateO(n)O(1)Best for interviews and readable implementations with explicit validation logic
Regular Expression ValidationO(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?
Validate IP Address is rated Medium because the logic is straightforward but requires careful handling of edge cases. Leading zeros, invalid hexadecimal characters, incorrect segment counts, and numeric range limits make the implementation error-prone if not checked systematically.
How to solve Validate IP Address in O(n)?
Scan the string once by splitting it into segments based on '.' or ':'. Validate each segment individually—check numeric ranges for IPv4 and hexadecimal character rules for IPv6. Since each character participates in a constant number of checks, the total runtime remains linear in the input length.
What is the best approach for Validate IP Address?
The split-and-validate approach is the most common solution. Split the string by '.' for IPv4 or ':' for IPv6, then validate segment count, allowed characters, and numeric ranges. This approach runs in O(n) time and uses O(1) extra space while keeping the validation logic explicit and easy to debug.
What data structure is used in Validate IP Address?
The solution mainly relies on string operations and small arrays or lists produced by splitting the input string. No advanced data structures are required; simple iteration and character validation handle the constraints efficiently.
What is the time complexity of Validate IP Address?
Both common approaches run in O(n) time where n is the length of the input string. Each character is examined at most once during splitting or regex matching. Space complexity is O(1) because only a fixed number of segments are stored during validation.
Validate IP Address Python or Java solution approach
In Python or JavaScript, developers often implement the split-and-validate method using built-in string functions like split and character checks. In Java or C#, regex-based validation is also common, where predefined patterns enforce IPv4 or IPv6 formatting rules.
Is Validate IP Address asked at Google, Amazon, or Meta?
String validation and parsing problems similar to Validate IP Address appear in interviews at companies like Amazon, Google, and Meta. They test careful handling of edge cases, input parsing, and rule-based validation using basic string manipulation.

Ready to solve this problem?

Practice Validate IP Address with our built-in code editor and test cases.

Practice on FleetCode