#3657
Find Loyal Customers
MediumHash MapArray
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)
Use a single pass to aggregate data for each customer, reducing the need for multiple scans.
⚙️
Algorithm
3 steps- 1Step 1: Create a summary table for each customer with counts of purchases, refunds, and transaction dates.
- 2Step 2: Calculate the refund rate and check the activity duration in one pass.
- 3Step 3: Filter customers based on loyalty criteria and return the result.
solution.py1 lines
1SELECT customer_id FROM (SELECT customer_id, COUNT(CASE WHEN transaction_type = 'purchase' THEN 1 END) AS purchase_count, COUNT(CASE WHEN transaction_type = 'refund' THEN 1 END) AS refund_count, MAX(transaction_date) AS last_date, MIN(transaction_date) AS first_date FROM customer_transactions GROUP BY customer_id) AS stats WHERE purchase_count >= 3 AND refund_count / (purchase_count + refund_count) < 0.2 AND DATEDIFF(last_date, first_date) >= 30;ℹ
Complexity note: Single pass through transactions allows for linear time complexity.
- 1Understanding refund rates is crucial for determining loyalty.
- 2Tracking transaction dates helps assess customer activity duration.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.