#183

Customers Who Never Order

Easy
DatabaseHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

The optimal approach uses a single query with a LEFT JOIN to efficiently find customers without orders. This reduces the need for nested loops and improves performance.

⚙️

Algorithm

3 steps
  1. 1Step 1: Perform a LEFT JOIN between Customers and Orders on the customer ID.
  2. 2Step 2: Filter the results where the order ID is NULL, indicating no orders.
  3. 3Step 3: Select the customer names from the filtered results.
solution.py1 lines
1SELECT c.name AS Customers FROM Customers c LEFT JOIN Orders o ON c.id = o.customerId WHERE o.id IS NULL;

Complexity note: The time complexity is O(n) because we are scanning through the Customers and Orders tables once, and the space complexity is O(n) due to the result set.

  • 1Using JOINs can significantly reduce the complexity of queries by eliminating the need for nested loops.
  • 2Understanding NULL values in SQL is crucial for identifying missing relationships.

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