#3451

Find Invalid IP Addresses

Hard
DatabaseString ManipulationRegular Expressions
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

Use a single pass to validate each IP address, leveraging string operations for efficiency.

⚙️

Algorithm

3 steps
  1. 1Step 1: Split the IP address by '.' and check the number of segments.
  2. 2Step 2: Validate each segment: check if it's a digit, within range, and has no leading zeros.
  3. 3Step 3: Count invalid IPs and order the results.
solution.py1 lines
1SELECT ip, COUNT(*) AS invalid_count FROM logs WHERE (LENGTH(ip) - LENGTH(REPLACE(ip, '.', '')) != 3 OR ip REGEXP '(^|\.)0[0-9]+\.' OR ip REGEXP '\\b[0-9]{3,}\\b' OR ip REGEXP '^[^0-9]|[^0-9]$') GROUP BY ip ORDER BY invalid_count DESC, ip DESC;

Complexity note: Single pass through IPs makes it linear; space for storing results.

  • 1Leading zeros invalidate an IP.
  • 2Each octet must be between 0 and 255.

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