#468

Validate IP Address

Medium
StringRegexString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a single pass to check the format of the IP address, utilizing regular expressions for validation. This reduces the number of checks and improves efficiency.

⚙️

Algorithm

5 steps
  1. 1Step 1: Check if the input matches the IPv4 regex pattern.
  2. 2Step 2: If it matches, return 'IPv4'.
  3. 3Step 3: Check if the input matches the IPv6 regex pattern.
  4. 4Step 4: If it matches, return 'IPv6'.
  5. 5Step 5: If neither matches, return 'Neither'.
solution.py10 lines
1import re
2
3def validate_ip(queryIP):
4    ipv4_pattern = r'^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
5    ipv6_pattern = r'^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^([0-9a-fA-F]{1,4}:){1,7}:$|^::([0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4}$'
6    if re.match(ipv4_pattern, queryIP):
7        return 'IPv4'
8    if re.match(ipv6_pattern, queryIP):
9        return 'IPv6'
10    return 'Neither'

Complexity note: The time complexity is O(n) because we only scan the string once to match against the regex patterns. The space complexity is O(1) as we are not using any additional data structures that grow with input size.

  • 1Understanding the structure of IP addresses is crucial for validation.
  • 2Regular expressions can significantly simplify the validation process.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.