Validate IP Address - Problem
In today's interconnected world, every device on the internet needs a unique address - an IP address. Your task is to build a smart validator that can distinguish between different IP address formats!
Given a string queryIP, you need to determine if it represents a valid IPv4 address, a valid IPv6 address, or neither.
IPv4 Rules:
- Format:
"x₁.x₂.x₃.x₄"(exactly 4 parts separated by dots) - Each part must be a number between 0 and 255
- No leading zeros allowed (except for "0" itself)
- Example:
"192.168.1.1"✅,"192.168.01.1"❌
IPv6 Rules:
- Format:
"x₁:x₂:x₃:x₄:x₅:x₆:x₇:x₈"(exactly 8 parts separated by colons) - Each part is 1-4 hexadecimal characters (0-9, a-f, A-F)
- Leading zeros are allowed
- Example:
"2001:0db8:85a3:0000:0000:8a2e:0370:7334"✅
Return: "IPv4", "IPv6", or "Neither"
Input & Output
example_1.py — Valid IPv4 Address
$
Input:
queryIP = "192.168.1.1"
›
Output:
"IPv4"
💡 Note:
This is a valid IPv4 address with 4 parts separated by dots, each part is between 0-255 with no leading zeros.
example_2.py — Valid IPv6 Address
$
Input:
queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334"
›
Output:
"IPv6"
💡 Note:
This is a valid IPv6 address with 8 parts separated by colons, each part contains 1-4 hexadecimal characters.
example_3.py — Invalid Address
$
Input:
queryIP = "256.256.256.256"
›
Output:
"Neither"
💡 Note:
Although this has the IPv4 format, each part exceeds 255, making it invalid.
Visualization
Tap to expand
Understanding the Visualization
1
Type Detection
Check for '.' (IPv4) or ':' (IPv6) separators
2
Component Splitting
Split the string into parts using the detected separator
3
Count Validation
Verify we have exactly 4 parts (IPv4) or 8 parts (IPv6)
4
Component Validation
Apply type-specific rules to each component
Key Takeaway
🎯 Key Insight: Separate concerns by first identifying the IP type, then applying type-specific validation rules. This makes the code cleaner and easier to debug.
Time & Space Complexity
Time Complexity
O(n)
We still need to examine each character once, but with more overhead
✓ Linear Growth
Space Complexity
O(1)
Only using a few variables to track state
✓ Linear Space
Constraints
-
queryIPconsists only of English letters, digits and the characters'.'and':' -
1 ≤
queryIP.length≤ 100
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code