Find Products with Three Consecutive Digits Problem
#3415
Description
LeetCode Problem 3415.
Table: Products
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| product_id | int |
| name | varchar |
+-------------+---------+
product_id is the unique key for this table.
Each row of this table contains the ID and name of a product.
Write a solution to find all products whose names contain a sequence of exactly three consecutive digits in a row.
Return the result table ordered by product_id in ascending order.
The result format is in the following example.
Note that the name may contain multiple such sequences, but each should have length three.
Example:
Input:
products table:
+-------------+--------------------+
| product_id | name |
+-------------+--------------------+
| 1 | ABC123XYZ |
| 2 | A12B34C |
| 3 | Product56789 |
| 4 | NoDigitsHere |
| 5 | 789Product |
| 6 | Item003Description |
| 7 | Product12X34 |
+-------------+--------------------+
Output:
+-------------+--------------------+
| product_id | name |
+-------------+--------------------+
| 1 | ABC123XYZ |
| 5 | 789Product |
| 6 | Item003Description |
+-------------+--------------------+
Explanation:
- Product 1: ABC123XYZ contains the digits 123.
- Product 5: 789Product contains the digits 789.
- Product 6: Item003Description contains 003, which is exactly three digits.
Note:
- Results are ordered by product_id in ascending order.
- Only products with exactly three consecutive digits in their names are included in the result.
Solution
Approach: Regular expression with non-digit boundaries
The name must contain a run of digits whose length is exactly 3. A bare [0-9]{3} would also match inside 56789, so the run has to be bounded on both sides by something that is not a digit, or by the start or end of the string:
(^|[^0-9])[0-9]{3}([^0-9]|$)
Item003Description:m003Dmatches, sincemandDare not digits, so the product is returned. Leading zeros do not matter.Product56789: every window of three digits has a digit next to it, so there is no match.A12B34CandProduct12X34: the digit runs have length 2, so there is no match.789Product: the run starts at the beginning of the string and is allowed by the^alternative.
A name with several digit runs is returned when at least one of them has length 3. The Pandas version uses the same pattern with str.contains.
SELECT product_id, name
FROM Products
WHERE name REGEXP '(^|[^0-9])[0-9]{3}([^0-9]|$)'
ORDER BY product_id;