#1934
Confirmation Rate
MediumDatabaseHash MapAggregation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages SQL's aggregation capabilities to compute the confirmation rates in a single query. By using a LEFT JOIN and aggregation functions, we can efficiently calculate the required rates without nested loops.
⚙️
Algorithm
6 steps- 1Step 1: Perform a LEFT JOIN between the Signups and Confirmations tables on user_id.
- 2Step 2: Use aggregation functions to count confirmed actions and total actions for each user.
- 3Step 3: Calculate the confirmation rate using the counts obtained.
- 4Step 4: Use COALESCE to handle users with no confirmation requests, ensuring the rate is 0.
- 5Step 5: Round the confirmation rate to two decimal places.
- 6Step 6: Return the user_id and confirmation rate.
solution.py5 lines
1# Full working Python code
2SELECT s.user_id, ROUND(COALESCE(SUM(CASE WHEN c.action = 'confirmed' THEN 1 ELSE 0 END) / COUNT(c.action), 0), 2) AS confirmation_rate
3FROM Signups s
4LEFT JOIN Confirmations c ON s.user_id = c.user_id
5GROUP BY s.user_id;ℹ
Complexity note: The time complexity is O(n) because we are processing each row in the Signups and Confirmations tables once, leveraging SQL's built-in aggregation functions.
- 1Understanding the difference between confirmed and total requests is crucial.
- 2Using SQL's aggregation functions can significantly reduce complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.