diff --git a/README.md b/README.md index 0bb5d95..c2a53b1 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/leetcode/hard/3451. Find Invalid IP Addresses.sql b/leetcode/hard/3451. Find Invalid IP Addresses.sql new file mode 100644 index 0000000..d66f7a5 --- /dev/null +++ b/leetcode/hard/3451. Find Invalid IP Addresses.sql @@ -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