|
| 1 | +/* |
| 2 | +Question 3451. Find Invalid IP Addresses |
| 3 | +Link: https://leetcode.com/problems/find-invalid-ip-addresses/description/?envType=problem-list-v2&envId=database |
| 4 | +
|
| 5 | +Table: logs |
| 6 | +
|
| 7 | ++-------------+---------+ |
| 8 | +| Column Name | Type | |
| 9 | ++-------------+---------+ |
| 10 | +| log_id | int | |
| 11 | +| ip | varchar | |
| 12 | +| status_code | int | |
| 13 | ++-------------+---------+ |
| 14 | +log_id is the unique key for this table. |
| 15 | +Each row contains server access log information including IP address and HTTP status code. |
| 16 | +Write a solution to find invalid IP addresses. An IPv4 address is invalid if it meets any of these conditions: |
| 17 | +
|
| 18 | +Contains numbers greater than 255 in any octet |
| 19 | +Has leading zeros in any octet (like 01.02.03.04) |
| 20 | +Has less or more than 4 octets |
| 21 | +Return the result table ordered by invalid_count, ip in descending order respectively. |
| 22 | +*/ |
| 23 | + |
| 24 | +SELECT |
| 25 | + ip, |
| 26 | + COUNT(ip) AS invalid_count |
| 27 | +FROM logs |
| 28 | +WHERE |
| 29 | + ARRAY_LENGTH(STRING_TO_ARRAY(ip, '.'), 1) != 4 |
| 30 | + OR LEFT(SPLIT_PART(ip, '.', 1), 1) = '0' |
| 31 | + OR LEFT(SPLIT_PART(ip, '.', 2), 1) = '0' |
| 32 | + OR LEFT(SPLIT_PART(ip, '.', 3), 1) = '0' |
| 33 | + OR LEFT(SPLIT_PART(ip, '.', 4), 1) = '0' |
| 34 | + OR SPLIT_PART(ip, '.', 1)::numeric > 255 |
| 35 | + OR SPLIT_PART(ip, '.', 2)::numeric > 255 |
| 36 | + OR SPLIT_PART(ip, '.', 3)::numeric > 255 |
| 37 | + OR SPLIT_PART(ip, '.', 4)::numeric > 255 |
| 38 | +GROUP BY ip |
| 39 | +ORDER BY invalid_count DESC, ip DESC |
0 commit comments