Skip to content
Problem 468 · LeetCode 468(opens in a new tab)

Validate IP Address

MediumStrings

You are given a string queryIP. Return "IPv4" if it is a valid IPv4 address, "IPv6" if it is a valid IPv6 address, and "Neither" otherwise.

An IPv4 address is four decimal numbers joined by dots. Each number is between 0 and 255 and has no extra zeros in front: 0 is fine, 00 and 012 are not.

An IPv6 address is eight groups joined by colons. Each group has 1 to 4 hexadecimal digits: 0 to 9, a to f or A to F. Zeros in front are allowed here, so 0012 is fine, but a group can never be empty.

Example 1

Input:  queryIP = "10.4.250.9"
Output: "IPv4"
Why:    four parts, each from 0 to 255, no leading zeros
2 more examples and the constraints

Example 2

Input:  queryIP = "fe80:0:0:0:1c:B3ff:abcd:0012"
Output: "IPv6"
Why:    eight hex groups of 1 to 4 digits

Example 3

Input:  queryIP = "10.4.250.09"
Output: "Neither"
Why:    "09" has a leading zero

Constraints

  • queryIP holds only English letters, digits, . and :
  • Those characters may come in any mix and order

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Regular expressionsO(n)
  2. Split and check each partO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeWork for one addressVerdict
Regular expressionsO(n)
Passes; the pattern is easy to get wrong
Split and check each partO(n)
Best; each rule is explicit

n = length of queryIP.

Edge cases to test

  • Leading zeros. 0 is a valid IPv4 part, 00 and 09 are not. In IPv6, 0012 is fine.
  • Empty parts. 10..4.250 and a trailing . or : give an empty part. Keep empty parts when splitting so they fail.
  • Values above 255. 300 has three digits but is too big. Check the length before parsing so a long part cannot overflow.
  • The IPv6 shorthand. :: is real-world shorthand for zero groups, but here it makes an empty group, so it is "Neither".
  • Mixed separators. A string with both . and : fits neither format.

Common mistakes

  • Using Java’s split("\\.") without -1, which drops trailing empty parts so 1.2.3.4. looks valid.
  • Allowing + or - in a part because a number parser accepts them.
  • Checking leading zeros in IPv6 groups too, where they are allowed.

How to talk through it

  1. 1Clarify. Are leading zeros allowed? Is the :: shorthand allowed? Can parts be empty?
  2. 2Pick the format. Three dots means try IPv4, seven colons means try IPv6, anything else is "Neither".
  3. 3List the rules. Say each rule per part out loud before coding: length, characters, leading zero, range.
  4. 4Code the checks. Split keeping empty parts and return "Neither" on the first broken rule.
  5. 5Test out loud. Try 0.0.0.0, 09, 256, an empty part and a five-digit IPv6 group.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?