Problem
Table: Signups
+----------------+----------+
| Column Name | Type |
+----------------+----------+
| user_id | int |
| time_stamp | datetime |
+----------------+----------+
user_id is the column with unique values for this table.
Each row contains information about the signup time for the user with ID user_id.
Table: Confirmations
+----------------+----------+
| Column Name | Type |
+----------------+----------+
| user_id | int |
| time_stamp | datetime |
| action | ENUM |
+----------------+----------+
(user_id, time_stamp) is the primary key (combination of columns with unique values) for this table.
user_id is a foreign key (reference column) to the Signups table.
action is an ENUM (category) of the type ('confirmed', 'timeout') Each row of this table indicates that the user with ID user_id requested a confirmation message at time_stamp and that confirmation message was either confirmed ('confirmed') or expired without confirming ('timeout').
Write a solution to find the IDs of the users that requested a confirmation message twice within a 24-hour window. Two messages exactly 24 hours apart are considered to be within the window. The action
does not affect the answer, only the request time.
Return the result table in any order.
The result format is in the following example.
Examples
Example 1:
|
|
Solution
Method 1 – Self-Join and Window Functions
Intuition
We want to find users who have at least two confirmation requests within a 24-hour window. We can self-join the Confirmations table on user_id and check if the time difference between any two requests is less than or equal to 24 hours.
Approach
- Self-join the Confirmations table on user_id, ensuring the first timestamp is less than the second.
- Check if the time difference between the two requests is less than or equal to 24 hours.
- Select distinct user_ids that satisfy this condition.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
— Self-join on Confirmations table. - 🧺 Space complexity:
O(1)
— No extra space beyond result set.