374/670

374. Validate IP Address

Medium

You are given a string query. Decide which kind of IP address it is, returning exactly one of the strings "IPv4", "IPv6", or "Neither".

A valid IPv4 address is four decimal chunks joined by dots, a.b.c.d, where each chunk is an integer from 0 to 255 written with no surplus leading zeros: "0" and "172" are fine, "01" and "256" are not.

A valid IPv6 address is eight groups joined by colons, x1:x2:x3:x4:x5:x6:x7:x8, where each group is 1 to 4 hexadecimal digits (09, af, AF). Leading zeros inside a group are allowed, but an empty group is not — so the :: shorthand never counts as valid here.

Anything else — wrong chunk count, stray characters, an empty chunk from a doubled or trailing separator — is "Neither".

Example 1:

Input: query = "172.16.254.1"

Output: "IPv4"

Explanation: Four dot-separated chunks, each between 0 and 255 with no extra leading zeros.

Example 2:

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

Output: "IPv6"

Explanation: Eight colon-separated groups of 1–4 hex digits. Leading zeros ("0db8") and mixed case ("8A2E") are both allowed.

Example 3:

Input: query = "256.256.256.256"

Output: "Neither"

Explanation: Every chunk exceeds 255, so it is not a valid IPv4 address, and it has no colons so it cannot be IPv6.

Constraints:

  • 1 ≤ query.length ≤ 60
  • query consists only of English letters, digits, '.' and ':'

Hints:

First decide which format to even attempt: a real answer never mixes separators, so three dots (and no colon) points at IPv4, seven colons (and no dot) at IPv6.

Split on the separator and validate each chunk on its own. Watch out: many split routines silently drop trailing empty chunks, so "1.2.3.4." can sneak through as four chunks — in Java use split("\\.", -1).

IPv4 chunk checklist: 1–3 characters, all decimal digits, no leading zero unless the chunk is exactly "0", numeric value ≤ 255. IPv6 group checklist: 1–4 characters, all hex digits.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: query = "172.16.254.1"

Expected output: "IPv4"