#3451
Find Invalid IP Addresses
HardDatabaseString ManipulationRegular Expressions
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal 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- 1Step 1: Split the IP address by '.' and check the number of segments.
- 2Step 2: Validate each segment: check if it's a digit, within range, and has no leading zeros.
- 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.