Find Invalid IP Addresses Problem
Description
LeetCode Problem 3451.
Table: logs
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| log_id | int |
| ip | varchar |
| status_code | int |
+-------------+---------+
log_id is the unique key for this table.
Each row contains server access log information including IP address and HTTP status code.
Write a solution to find invalid IP addresses. Each octet in an IP address contains between 1 and 3 digits. An IPv4 address is invalid if it meets any of these conditions:
- Contains a number greater than
255in any octet. - Has leading zeros in any octet (for example,
01.02.03.04). - Has fewer or more than
4octets.
Return the result table ordered by invalid_count, ip in descending order respectively.
The result format is in the following example.
Example:
Input:
logs table:
+--------+---------------+-------------+
| log_id | ip | status_code |
+--------+---------------+-------------+
| 1 | 192.168.1.1 | 200 |
| 2 | 256.1.2.3 | 404 |
| 3 | 192.168.001.1 | 200 |
| 4 | 192.168.1.1 | 200 |
| 5 | 192.168.1 | 500 |
| 6 | 256.1.2.3 | 404 |
| 7 | 192.168.001.1 | 200 |
+--------+---------------+-------------+
Output:
+---------------+--------------+
| ip | invalid_count|
+---------------+--------------+
| 256.1.2.3 | 2 |
| 192.168.001.1 | 2 |
| 192.168.1 | 1 |
+---------------+--------------+
Explanation:
- 256.1.2.3 is invalid because 256 > 255
- 192.168.001.1 is invalid because of leading zeros
- 192.168.1 is invalid because it has only 3 octets
The output table is ordered by invalid_count, ip in descending order respectively.
Solution
Approach: Describe a valid address, count the rest
It is easier to write down what a valid IPv4 address looks like than to list every way one can fail. A valid address has exactly four octets separated by dots, and each octet is a number from 0 to 255 written without leading zeros. One octet is any of:
25[0-5], which is 250 to 255;2[0-4][0-9], which is 200 to 249;1[0-9]{2}, which is 100 to 199;[1-9]?[0-9], which is 0 to 99 with no leading zero (7and42match,07does not).
The full pattern is ^OCTET(\.OCTET){3}$. The anchors and the fixed repetition {3} reject addresses with fewer or more than four octets, and the octet alternatives reject values above 255 and leading zeros such as 001. An address that does not match is invalid. Group the invalid rows by ip, count them, and order by invalid_count DESC, ip DESC. Note that the sort on ip is textual, so 256.1.2.3 comes before 192.168.001.1.
In a MySQL string literal each backslash has to be doubled (\\.). The Pandas version uses the same pattern with str.fullmatch and value_counts.
SELECT ip, COUNT(*) AS invalid_count
FROM logs
WHERE ip NOT REGEXP
'^(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}$'
GROUP BY ip
ORDER BY invalid_count DESC, ip DESC;