Find Products with Three Consecutive Digits solution and explanation
The problem
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_idin ascending order. - Only products with exactly three consecutive digits in their names are included in the result.
Approach overview
Problem Overview: You get a table of products. Return the products whose name contains three consecutive digits anywhere in the string. Digits must be adjacent, so "A1B2C3" fails and "Item 472" passes.
Approach 1: Character Scan (O(n * L) time, O(1) space)
Loop through each name character by character. Keep a counter of consecutive digit characters. Reset it to zero on any non-digit. If the counter reaches 3, the name matches and you can stop early. This works in any language or engine, but you write the loop yourself. Use it when the database lacks regex support and you need a portable check. Here n is the number of rows and L is the average name length.
Approach 2: Regex Matching (O(n * L) time, O(1) extra space)
Compile one pattern, [0-9]{3}, and test every name against it. The regex engine does the sliding window for you. In MySQL, filter with WHERE name REGEXP '[0-9]{3}'. In Pandas, use df[df['name'].str.contains(r'[0-9]{3}', regex=True)]. This is the approach to write in an interview or on the job. The pattern matches exactly three digits in a row, so a four-digit run still matches because it contains a three-digit run.
Recommended for interviews: Interviewers expect the regex filter. The character scan shows you understand the sliding window and the reset logic. The regex solution shows you know the right tool for pattern matching and can write the query in one line. Mention the manual scan first, then switch to regex and explain why it is cleaner. Both have the same asymptotic cost, so the win is readability and correctness.
Related topics: strings, sliding window, database.
Solution
Thinking
We need products whose names contain three consecutive digits. A hand-rolled scan easily misses boundaries between digits and letters or string ends.
A single regular expression covers those cases. The pattern
(^|[^0-9])[0-9]{3}([^0-9]|)matches an isolated run of three digits without treating a longer digit block as several overlapping hits in an uncontrolled way.We filter the frame with that pattern and sort by product_id$ to match the required order.
We can use regular expressions to match product names that contain three consecutive digits.
# Write your MySQL query statement below
SELECT product_id, name
FROM Products
WHERE name REGEXP '(^|[^0-9])[0-9]{3}([^0-9]|$)'
ORDER BY 1;import pandas as pd
def find_products(products: pd.DataFrame) -> pd.DataFrame:
filtered = products[
products["name"].str.contains(r"(^|[^0-9])[0-9]{3}([^0-9]|$)", regex=True)
]
return filtered.sort_values(by="product_id")Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Character Scan | O(n * L) | O(1) | No regex support, or you need explicit control over the logic |
| Regex Matching | O(n * L) | O(1) | General case in MySQL or Pandas, and the best default answer |
Frequently asked questions
Is Find Products with Three Consecutive Digits easy or hard?
It is easy. The acceptance rate is about 80 percent, and the solution is a single regex filter. The main challenge is knowing that [0-9]{3} matches a run of exactly three adjacent digits and that longer runs still match.
How to solve Find Products with Three Consecutive Digits in O(n)?
Scan each name once and track a running count of consecutive digit characters. Reset the count on any non-digit and return the row as soon as the count hits 3. Treat L as a constant for the per-name check, which gives linear time in total input size.
Find Products with Three Consecutive Digits Python or Java solution?
In Python, use re.search(r'[0-9]{3}', name) on each name, or filter a Pandas DataFrame with str.contains(r'[0-9]{3}', regex=True). In Java, use Pattern.compile("[0-9]{3}").matcher(name).find() on each row. The core logic is the same: one regex check per name.
What is the best approach for Find Products with Three Consecutive Digits?
The best approach is regex matching with the pattern [0-9]{3}. It filters rows in one step in MySQL with REGEXP or in Pandas with str.contains. Both run in O(n * L) time, where n is the row count and L is the average name length.
What data structure is used in Find Products with Three Consecutive Digits?
No special data structure is required. You work on strings and the regex engine, which uses a finite automaton internally. The table rows are the only data structure you query.
What is the time complexity of Find Products with Three Consecutive Digits?
The time complexity is O(n * L), where n is the number of products and L is the average length of each name. Each name is scanned once. The extra space is O(1) because the pattern is fixed and no new structures are built.
Is Find Products with Three Consecutive Digits asked at Google, Amazon, or Meta?
This problem is a basic SQL and string-matching exercise, so it is not tied to a single company in our tag data. It appears in SQL practice sets and warm-up rounds. Expect similar pattern-matching questions in database screens at large tech companies.