Validate IP Address (LeetCode 468): Solution and Explanation
Decide whether a string is a valid IPv4 address, a valid IPv6 address, or neither, and return "IPv4", "IPv6" or "Neither".
Intuition
Both formats are a fixed number of pieces joined by one separator: 4 pieces joined by dots for IPv4, 8 joined by colons for IPv6. So the separator count alone tells you which format could possibly match.
Once you split, each piece is independent. A piece is valid or not based only on its own characters, so the address is valid exactly when every piece passes.
The rules per piece are short. IPv4: 1 to 3 digits, no leading zero, at most 255. IPv6: 1 to 4 hex digits. Writing them as a checklist keeps the edge cases from slipping through.
Approach: Split and check each piece
- Count the dots. If there are exactly 3, split on
.(keeping empty pieces) and check each piece: not empty, at most 3 characters, only digits, no leading zero unless it is"0", value at most 255. If all pass, return"IPv4", otherwise"Neither". - Otherwise count the colons. If there are exactly 7, split on
:and check each group: not empty, at most 4 characters, only0-9,a-f,A-F. If all pass, return"IPv6", otherwise"Neither". - If neither separator count matches, return
"Neither".
Step-by-step example
queryIP = "172.16.254.1"
- The string has 3 dots and 0 colons, so test it as IPv4.
- Splitting on
.gives"172","16","254","1". "172"is 3 digits, has no leading zero and 172 <= 255. It passes."16","254"and"1"pass the same checks.- All four pieces pass, so the answer is
"IPv4".
Code: Python, Java, C++
1class Solution:
2 def validIPAddress(self, queryIP: str) -> str:
3 if queryIP.count('.') == 3:
4 parts = queryIP.split('.')
5 for p in parts:
6 if not p or len(p) > 3 or not p.isdigit():
7 return "Neither"
8 if (p[0] == '0' and len(p) > 1) or int(p) > 255:
9 return "Neither"
10 return "IPv4"
11 if queryIP.count(':') == 7:
12 parts = queryIP.split(':')
13 hexdigits = '0123456789abcdefABCDEF'
14 for p in parts:
15 if not p or len(p) > 4 or not all(c in hexdigits for c in p):
16 return "Neither"
17 return "IPv6"
18 return "Neither"1class Solution {
2 public String validIPAddress(String queryIP) {
3 if (count(queryIP, '.') == 3) {
4 String[] parts = queryIP.split("\\.", -1);
5 for (String p : parts) {
6 if (p.isEmpty() || p.length() > 3 || !allIn(p, "0123456789")) {
7 return "Neither";
8 }
9 if ((p.charAt(0) == '0' && p.length() > 1) || Integer.parseInt(p) > 255) {
10 return "Neither";
11 }
12 }
13 return "IPv4";
14 }
15 if (count(queryIP, ':') == 7) {
16 String[] parts = queryIP.split(":", -1);
17 for (String p : parts) {
18 if (p.isEmpty() || p.length() > 4 || !allIn(p, "0123456789abcdefABCDEF")) {
19 return "Neither";
20 }
21 }
22 return "IPv6";
23 }
24 return "Neither";
25 }
26
27 private int count(String s, char c) {
28 int k = 0;
29 for (char ch : s.toCharArray()) {
30 if (ch == c) k++;
31 }
32 return k;
33 }
34
35 private boolean allIn(String p, String allowed) {
36 for (char ch : p.toCharArray()) {
37 if (allowed.indexOf(ch) < 0) return false;
38 }
39 return true;
40 }
41}1class Solution {
2public:
3 string validIPAddress(string queryIP) {
4 if (count(queryIP.begin(), queryIP.end(), '.') == 3) {
5 vector<string> parts = split(queryIP, '.');
6 for (const string& p : parts) {
7 if (p.empty() || p.size() > 3 || !allIn(p, "0123456789")) {
8 return "Neither";
9 }
10 if ((p[0] == '0' && p.size() > 1) || stoi(p) > 255) {
11 return "Neither";
12 }
13 }
14 return "IPv4";
15 }
16 if (count(queryIP.begin(), queryIP.end(), ':') == 7) {
17 vector<string> parts = split(queryIP, ':');
18 for (const string& p : parts) {
19 if (p.empty() || p.size() > 4 || !allIn(p, "0123456789abcdefABCDEF")) {
20 return "Neither";
21 }
22 }
23 return "IPv6";
24 }
25 return "Neither";
26 }
27
28private:
29 vector<string> split(const string& s, char d) {
30 vector<string> out;
31 string cur;
32 for (char c : s) {
33 if (c == d) {
34 out.push_back(cur);
35 cur.clear();
36 } else {
37 cur += c;
38 }
39 }
40 out.push_back(cur);
41 return out;
42 }
43
44 bool allIn(const string& p, const string& allowed) {
45 for (char c : p) {
46 if (allowed.find(c) == string::npos) return false;
47 }
48 return true;
49 }
50};Time and space complexity
O(n)
Counting, splitting and checking each character are all linear in the length of the string.
O(n)
The split pieces together hold every character of the input.
Other approaches
Regular expressions (time O(n), space O(1))
Write one pattern per family, such as (25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d) repeated for IPv4 octets and [0-9a-fA-F]{1,4} for IPv6 groups. Compact, but easy to get subtly wrong and harder to explain in an interview.
Library parsers (time O(n), space O(n))
Many languages have an address parser, but they often accept forms this problem rejects, such as :: compression or leading zeros, so they need extra checks anyway.
Common mistakes
- Splitting in a way that drops empty pieces. Java's
splitdrops trailing empty strings unless you pass-1, so"1.1.1.1."would wrongly look like 4 pieces. - Forgetting that
"0"is a valid IPv4 piece while"00"and"01"are not. - Parsing a long digit string as an integer before checking its length, which can overflow. Check the length first.
- Treating
::as valid. This problem does not allow IPv6 zero compression, so every group must have at least one character. - Allowing leading zeros to fail IPv6. In IPv6,
"0db8"is fine; only the length limit of 4 applies.
Frequently asked questions
Why count separators before splitting?
The counts tell you which format to test. A string with 3 dots can only be IPv4, and one with 7 colons can only be IPv6, so you never run both checks.
Is "0.0.0.0" valid?
Yes. Each piece is the single digit 0, which is allowed. Only multi-digit pieces that start with 0 are rejected.
Are uppercase hex letters allowed in IPv6?
Yes. Both a-f and A-F are valid, so "8A2E" and "8a2e" are both fine.
What are the time and space costs?
O(n) time to scan and split the string, and O(n) space for the pieces.