LeetCode Problem Workspace

Validate IP Address

Determine whether a given string is a valid IPv4 or IPv6 address using a precise string-driven validation strategy.

category

1

Topics

code_blocks

6

Code langs

hub

3

Related

Practice Focus

Medium · String-driven solution strategy

bolt

Answer-first summary

Determine whether a given string is a valid IPv4 or IPv6 address using a precise string-driven validation strategy.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for String-driven solution strategy

Try AiBox Copilotarrow_forward

This problem requires analyzing the input string to classify it as IPv4, IPv6, or neither. A string-driven approach ensures each segment is validated against format rules, avoiding incorrect leading zeros or invalid characters. By splitting the input and verifying numeric ranges or hexadecimal constraints, you can reliably determine the correct IP type without relying on external libraries.

Problem Statement

Given a string queryIP, write a function to determine if it represents a valid IPv4 address, a valid IPv6 address, or neither. Return "IPv4" if it matches the IPv4 format, "IPv6" if it matches IPv6 format, and "Neither" otherwise.

An IPv4 address consists of four decimal segments separated by dots, with each segment between 0 and 255 and no leading zeros. An IPv6 address consists of eight hexadecimal segments separated by colons, each segment containing 1 to 4 hexadecimal digits. The input only contains letters, digits, dots, and colons.

Examples

Example 1

Input: queryIP = "172.16.254.1"

Output: "IPv4"

This is a valid IPv4 address, return "IPv4".

Example 2

Input: queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334"

Output: "IPv6"

This is a valid IPv6 address, return "IPv6".

Example 3

Input: queryIP = "256.256.256.256"

Output: "Neither"

This is neither a IPv4 address nor a IPv6 address.

Constraints

  • queryIP consists only of English letters, digits and the characters '.' and ':'.

Solution Approach

Split and Validate Segments

For IPv4, split the string by '.' and check for exactly four parts. Each part must be numeric, in the range 0 to 255, and cannot have leading zeros. For IPv6, split by ':' and ensure there are eight segments, each with 1 to 4 hexadecimal digits.

Check Numeric and Hexadecimal Rules

Iterate over each segment: IPv4 segments must contain only digits, IPv6 segments must contain valid hexadecimal characters. Reject the input if any segment violates these rules. This ensures precise detection of invalid characters or ranges that commonly cause misclassification.

Return Result Based on Validation

If all segments pass the validation for IPv4, return 'IPv4'. If all pass for IPv6, return 'IPv6'. If neither validation succeeds, return 'Neither'. This clear separation prevents mixed-format strings from being incorrectly accepted.

Complexity Analysis

Metric Value
Time \mathcal{O}(N)
Space \mathcal{O}(1)

Time complexity is (\mathcal{O}(N)) since each character of the string is examined once. Space complexity is (\mathcal{O}(1)) ignoring the split segments array, as only fixed-size checks are used per segment.

What Interviewers Usually Probe

  • Expect clear string parsing and segment-by-segment validation.
  • Watch for handling of leading zeros and range violations in IPv4 segments.
  • Look for proper hexadecimal checks and correct segment count in IPv6 addresses.

Common Pitfalls or Variants

Common pitfalls

  • Allowing leading zeros in IPv4 segments, e.g., '01' incorrectly accepted.
  • Failing to check that each IPv6 segment has at most four hexadecimal digits.
  • Mixing IPv4 and IPv6 separators, or miscounting the number of segments.

Follow-up variants

  • Validate only IPv4 addresses, skipping IPv6 checks.
  • Validate only IPv6 addresses, skipping IPv4 checks.
  • Detect shorthand IPv6 formats with omitted zeros, extending the standard rules.

FAQ

What is the simplest method to determine if a string is IPv4 or IPv6?

Use a string-driven approach: split by '.' for IPv4 or ':' for IPv6, then validate segment counts, numeric ranges, and character rules.

Can leading zeros appear in valid IPv4 addresses?

No, IPv4 segments with leading zeros such as '01' are considered invalid and must be rejected.

How do I validate hexadecimal segments in IPv6?

Check that each segment contains 1 to 4 characters and consists only of 0-9, a-f, or A-F.

What should I return if the input string is neither IPv4 nor IPv6?

Return 'Neither' whenever the string fails either the IPv4 or IPv6 validation rules.

Why is Validate IP Address considered a string-driven problem?

The problem focuses on analyzing the string format and content without numerical conversion beyond validation, following a strict segment-based pattern.

terminal

Solution

Solution 1: Simulation

We can define two functions `isIPv4` and `isIPv6` to determine whether a string is a valid IPv4 address and IPv6 address.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
    def validIPAddress(self, queryIP: str) -> str:
        def is_ipv4(s: str) -> bool:
            ss = s.split(".")
            if len(ss) != 4:
                return False
            for t in ss:
                if len(t) > 1 and t[0] == "0":
                    return False
                if not t.isdigit() or not 0 <= int(t) <= 255:
                    return False
            return True

        def is_ipv6(s: str) -> bool:
            ss = s.split(":")
            if len(ss) != 8:
                return False
            for t in ss:
                if not 1 <= len(t) <= 4:
                    return False
                if not all(c in "0123456789abcdefABCDEF" for c in t):
                    return False
            return True

        if is_ipv4(queryIP):
            return "IPv4"
        if is_ipv6(queryIP):
            return "IPv6"
        return "Neither"
Validate IP Address Solution: String-driven solution strategy | LeetCode #468 Medium