#1581

Customer Who Visited but Did Not Make Any Transactions

Easy
DatabaseHash MapAggregationJOIN operations
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + m)
Space
O(1)
O(n)
💡

Intuition

Time O(n + m)Space O(n)

By using a HashMap to track transactions, we can efficiently determine which customers have made no transactions in a single pass through both tables.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a HashMap to count the number of visits for each customer.
  2. 2Step 2: Iterate through the Visits table and populate the HashMap with customer IDs and their visit counts.
  3. 3Step 3: Iterate through the Transactions table and reduce the count for each customer who has made a transaction.
  4. 4Step 4: Filter the HashMap to include only those customers with a count greater than zero, indicating no transactions.
solution.py16 lines
1# Full working Python code
2WITH VisitCounts AS (
3    SELECT customer_id, COUNT(*) AS visit_count
4    FROM Visits
5    GROUP BY customer_id
6),
7TransactionCounts AS (
8    SELECT v.customer_id, COUNT(*) AS trans_count
9    FROM Transactions t
10    JOIN Visits v ON t.visit_id = v.visit_id
11    GROUP BY v.customer_id
12)
13SELECT vc.customer_id, vc.visit_count AS count_no_trans
14FROM VisitCounts vc
15LEFT JOIN TransactionCounts tc ON vc.customer_id = tc.customer_id
16WHERE tc.trans_count IS NULL;

Complexity note: This complexity is linear because we are iterating through both the Visits and Transactions tables once, leading to a combined time complexity of O(n + m).

  • 1Understanding how to efficiently join and aggregate data is crucial in SQL.
  • 2Using EXISTS or JOIN can significantly improve performance over nested loops.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.