Validate IP Address

Given a string `queryIP`, return "IPv4" if it is a valid IPv4 address, "IPv6" if it is a valid IPv6 address, or "Neither" otherwise. A valid IPv4 address is four decimal numbers from 0 to 255 joined by dots, with no leading zeros ("192.168.1.1" is valid, "192.168.01.1" is not). A valid IPv6 address is eight groups of 1 to 4 hexadecimal digits (upper or lower case) joined by colons; leading zeros inside a group are allowed, but empty groups are not.

30:00

Validate IP Address
medium
Free written solution
Topics
Companies

Given a string queryIP, return "IPv4" if it is a valid IPv4 address, "IPv6" if it is a valid IPv6 address, or "Neither" otherwise. A valid IPv4 address is four decimal numbers from 0 to 255 joined by dots, with no leading zeros ("192.168.1.1" is valid, "192.168.01.1" is not). A valid IPv6 address is eight groups of 1 to 4 hexadecimal digits (upper or lower case) joined by colons; leading zeros inside a group are allowed, but empty groups are not.

Example 1:
Input: {"queryIP":"172.16.254.1"}
Output: IPv4
Constraints:
  • queryIP consists only of English letters, digits and the characters '.' and ':'.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"queryIP":"172.16.254.1"}

The string has 3 dots and 0 colons. The separators decide which family to test: IPv4 needs exactly 3 dots, IPv6 exactly 7 colons.

queryIP

1
7
2
.
1
6
.
2
5
4
.
1

'.' count = 3

IPv4 needs 3

':' count = 0

IPv6 needs 7

amber = piece under test · green = passed · red = failed

Variables
VariableValue
queryIP172.16.254.1
DepthFunction Call
Stack empty
0/11