468. Validate IP Address - Detailed Explanation

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

Problem Statement

Given a string representing an IP address, determine whether it is a valid IPv4 or IPv6 address or neither. An IPv4 address consists of four decimal numbers separated by dots. Each number must be between 0 and 255 and cannot have leading zeros (except for the number 0 itself). An IPv6 address consists of eight groups separated by colons. Each group is a hexadecimal number (digits 0-9 and letters a-f/A-F) and can contain from 1 to 4 hexadecimal digits.

Example 1
Input: "172.16.254.1"
Output: "IPv4"
Explanation: Each part (172, 16, 254, 1) is in the correct range and properly formatted.

Example 2
Input: "2001:0db8:85a3:0:0:8A2E:0370:7334"
Output: "IPv6"
Explanation: There are eight groups, and every group contains valid hexadecimal digits.

Example 3
Input: "256.256.256.256"
Output: "Neither"
Explanation: Each number in an IPv4 address must be between 0 and 255; here, 256 is out of range.

Constraints:
The input string is non-empty and contains only alphanumeric characters along with the characters '.' and ':'.

Hints

Hint 1: Check the separator in the string. If it contains dots ('.'), treat it as an IPv4 candidate; if it contains colons (':'), treat it as an IPv6 candidate.

Hint 2: For IPv4, validate that each segment is non-empty, contains only digits, has no leading zeros (unless the segment is exactly "0"), and represents a number between 0 and 255. For IPv6, ensure that each segment has between 1 and 4 characters and that every character is a valid hexadecimal digit (0-9, a-f, A-F).

Brute Force Approach

Idea: Split the input string by the expected separator ('.' for IPv4 and ':' for IPv6) and manually check each part against the required rules.
Steps:

  • IPv4 Check:
    • Split the string by "." and ensure there are exactly 4 parts.
    • For each part, check that it is non-empty, contains only digits, does not have leading zeros (unless it is "0"), and its integer value is between 0 and 255.
  • IPv6 Check:
    • Split the string by ":" and ensure there are exactly 8 parts.
    • For each part, ensure its length is between 1 and 4 and that every character is a valid hexadecimal digit.

Pros: Simple and easy to understand.
Cons: Involves multiple conditional checks, but overall time complexity remains linear.

Optimal Approach

Idea: Use the same splitting strategy but streamline the validation process. Optionally, regular expressions can be used for pattern matching; however, the explicit approach is often clearer for junior engineers.

Steps:

  • Determine the type by checking for a dot or a colon.
  • For IPv4, validate digit-only segments and use error handling while converting to numbers.
  • For IPv6, use a set of valid hexadecimal characters for quick lookup and validate each segment’s length and characters.

Pros: Clear logic with early termination on failure.
Cons: Regex might reduce code length but can compromise readability for beginners.

Python Code

Python3
Python3

. . . .

Java Code

Java
Java

. . . .

Complexity Analysis

  • Time Complexity: For both IPv4 and IPv6 validations, each character of the input string is processed at most once, yielding a time complexity of O(n), where n is the length of the string.

  • Space Complexity: O(n) in the worst case due to the space used when splitting the string into parts.

Step-by-Step Walkthrough (Visual Example)

For the input "172.16.254.1":

  • Step 1: Check if the input contains three dots; since it does, treat it as an IPv4 candidate.
  • Step 2: Split the string into ["172", "16", "254", "1"].
  • Step 3: Validate each segment: "172", "16", "254", and "1" are all non-empty, contain only digits, have no invalid leading zeros, and are within the 0-255 range.
  • Step 4: Since all segments are valid, the result is "IPv4".

Common Mistakes

  • Overlooking leading zeros in IPv4 segments (e.g., "01" or "001" are invalid).
  • Incorrectly handling splits that result in empty segments due to extra separators.
  • Failing to validate that each IPv6 segment contains only valid hexadecimal characters.
  • Mixing up the separators by not distinguishing between dots and colons.

Edge Cases

  • Addresses with trailing or leading separators (e.g., "1.1.1.1." or ".1.1.1.1") should return "Neither".
  • Addresses with an incorrect number of segments (e.g., "1.1.1" or "1:1:1:1:1:1:1") are invalid.
  • Addresses with empty segments (e.g., "192..168.1.1") are invalid.
  • IPv6 segments with more than 4 hexadecimal digits are invalid.

Alternative Variations:

  • Modifying the problem to accept compressed IPv6 notation (using "::") is an interesting twist.

  • Validating CIDR notations (e.g., "192.168.1.1/24") is a similar variation.

Related Problems for Further Practice:

TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
How do I ask for a job interview on LinkedIn?
How to crack coding round?
Design a URL Shortener System Interview Question
Learn how to design a URL shortener system for system design interviews. Explore database choices, hashing techniques, scalability strategies, and best practices.
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Image
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
Image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.
;