Leetcode #468: Validate IP Address
In this guide, we solve Leetcode #468 Validate IP Address in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given a string queryIP, return "IPv4" if IP is a valid IPv4 address, "IPv6" if IP is a valid IPv6 address or "Neither" if IP is not a correct IP of any type. A valid IPv4 address is an IP in the form "x1.x2.x3.x4" where 0 <= xi <= 255 and xi cannot contain leading zeros.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: String
Intuition
We need to scan characters while tracking positions or counts.
A simple state machine keeps the logic precise.
Approach
Iterate through the string once and update the state for each character.
Use a map or array if you need fast lookups.
Steps:
- Iterate through characters.
- Maintain necessary state.
- Build or validate the output.
Example
Input: queryIP = "172.16.254.1"
Output: "IPv4"
Explanation: This is a valid IPv4 address, return "IPv4".
Python Solution
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"
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.