Problem 468

Abstract / Summary

Check if a string is a valid IPv4 or IPv6 address according to standard rules.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0468.py

import socket
class Solution:
    def validIPAddress(self, queryIP: str) -> str:
        # use built-in IP parser
        try:
            # IPv4
            socket.inet_pton(socket.AF_INET, queryIP)
            return "IPv4"
        except socket.error:
            pass

        try:
            # IPv6
            socket.inet_pton(socket.AF_INET6, queryIP)
            if queryIP.count("::") == 0: # weird extra-condition of this problem
                return "IPv6"
        except socket.error:
            pass

        return "Neither"
20 lines | 563 bytes | submitted January 6, 2024 | GitHub   26% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 27% (600k+ submissions).

Typical patterns to solve this problem:
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided module defines a single class Solution with a method validIPAddress. The method receives a textual representation of an IP address and returns a string indicating whether the input conforms to IPv4, IPv6, or neither. The implementation relies on the operating-system level parsing facilities exposed through Python’s socket module, thereby delegating the heavy lifting of syntactic validation to a highly optimized native routine.

Key Steps

IPv4 validation

The first logical block attempts to interpret the input as an IPv4 address. A call to socket.inet_pton with the address family AF_INET is wrapped in a try statement. If the native parser accepts the string, the function immediately returns "IPv4". The surrounding except socket.error silently absorbs any parsing failure, allowing execution to continue to the next stage.

try:
    # IPv4
    socket.inet_pton(socket.AF_INET, queryIP)
    return "IPv4"
except socket.error:
    pass

IPv6 validation

If the IPv4 attempt fails, the method proceeds to a second try block that targets IPv6 syntax using AF_INET6. Upon successful parsing, an additional condition checks that the input does not contain the double-colon shorthand ("::"). This extra test reflects a problem-specific rule that disallows compressed IPv6 forms. When both the native validation and the count check succeed, the method returns "IPv6".

try:
    # IPv6
    socket.inet_pton(socket.AF_INET6, queryIP)
    if queryIP.count("::") == 0:  # problem-specific extra condition
        return "IPv6"
except socket.error:
    pass

Final fallback

When neither the IPv4 nor the IPv6 validation paths produce a result, the method reaches its concluding statement and returns "Neither". This default branch captures all inputs that are either malformed or violate the additional IPv6 restriction.

return "Neither"

Edge Cases Handled

The code gracefully manages several edge conditions without explicit string manipulation. An input that resembles an IPv4 address but contains out-of-range octets, non-numeric characters, or an incorrect number of segments triggers a socket.error, causing the flow to skip to the IPv6 check. Similarly, malformed IPv6 strings-such as those with too few or too many hextets, illegal characters, or misplaced colons-are rejected by the native parser, raising the same exception.

The explicit queryIP.count("::") == 0 guard addresses the special case where a valid IPv6 address uses the compression syntax. By counting occurrences of the double colon, the implementation filters out any address that employs this shorthand, ensuring compliance with the problem’s requirement that only fully expanded IPv6 forms are accepted.

Performance Optimizations

The most notable optimization stems from delegating validation to socket.inet_pton. This function is implemented in C and performs low-level parsing, which is substantially faster than a pure-Python regular-expression or manual tokenization approach. The early return after a successful IPv4 check prevents unnecessary execution of the IPv6 block, reducing the average work for typical IPv4 inputs.

The IPv6 branch includes a single count operation on the original string, which is an O(n) scan but is executed only after the expensive native parsing has already succeeded. This ordering ensures that the relatively cheap check for the prohibited "::" pattern does not precede the more costly validation, thereby avoiding redundant work for inputs that would be rejected by the parser anyway.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big pile of letters and numbers written on pieces of paper. Some of these papers follow the rules for a special address for computers, like a house address that tells your computer exactly where to go on the internet. There are two main styles for these addresses. One style is called IPv4 and the other is called IPv6.

The computer starts by trying to see if the paper matches the first style. It uses a special tool that is very good at reading addresses. If the tool says the address fits the first style perfectly, the computer knows it found an IPv4 address.

If that does not work, the computer tries the second style. It uses the tool again to see if the paper fits the rules for an IPv6 address. Sometimes there is an extra rule about how the address looks, and the computer checks for that too. If the address follows all the rules for the second style, the computer decides it is an IPv6 address.

If the paper does not fit either of these two styles, the computer decides that the address is something else entirely and does not count as either one.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.81 | σ = 1.33

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Rust Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
gouthampradhan Java
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
gouthampradhan Java
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
34 links | 20 authors | 9 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

10 solutions   January 6, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality