Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ Useful for preparing for technical interviews and improving your SQL skills.
- [185. Department Top Three Salaries](./leetcode/hard/185.%20Department%20Top%20Three%20Salaries.sql)
- [601. Human Traffic of Stadium](./leetcode/hard/601.%20Human%20Traffic%20of%20Stadium.sql)
- [3374. First Letter Capitalization II](./leetcode/hard/3374.%20First%20Letter%20Capitalization%20II.sql)
- [3451. Find Invalid IP Addresses](./leetcode/hard/3451.%20Find%20Invalid%20IP%20Addresses.sql)

## Contributing

Expand Down
39 changes: 39 additions & 0 deletions leetcode/hard/3451. Find Invalid IP Addresses.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
Question 3451. Find Invalid IP Addresses
Link: https://leetcode.com/problems/find-invalid-ip-addresses/description/?envType=problem-list-v2&envId=database

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. An IPv4 address is invalid if it meets any of these conditions:

Contains numbers greater than 255 in any octet
Has leading zeros in any octet (like 01.02.03.04)
Has less or more than 4 octets
Return the result table ordered by invalid_count, ip in descending order respectively.
*/

SELECT
ip,
COUNT(ip) AS invalid_count
FROM logs
WHERE
ARRAY_LENGTH(STRING_TO_ARRAY(ip, '.'), 1) != 4
OR LEFT(SPLIT_PART(ip, '.', 1), 1) = '0'
OR LEFT(SPLIT_PART(ip, '.', 2), 1) = '0'
OR LEFT(SPLIT_PART(ip, '.', 3), 1) = '0'
OR LEFT(SPLIT_PART(ip, '.', 4), 1) = '0'
OR SPLIT_PART(ip, '.', 1)::numeric > 255
OR SPLIT_PART(ip, '.', 2)::numeric > 255
OR SPLIT_PART(ip, '.', 3)::numeric > 255
OR SPLIT_PART(ip, '.', 4)::numeric > 255
GROUP BY ip
ORDER BY invalid_count DESC, ip DESC