EasyNo. 0183

Customers Who Never Order — LeetCode 183 Python Solution

Topics
Database
Reading time
2 min

The problem

List the customers who have never placed a single order. Customers has id (int, primary key) and name (varchar); Orders has id (int, primary key) and customerId (int), which references a customer. Return the names in a column called Customers.

Example

Input
Customers(id, name) = (1, 'Ana'), (2, 'Ben'), (3, 'Cleo'), (4, 'Dev'); Orders(id, customerId) = (1, 3), (2, 1)
Output
Customers = 'Ben', 'Dev'
Explanation
Orders exist only for customers 1 and 3, so Ben and Dev never ordered.

Python solution

PythonSolution
import pandas as pd


def find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:
    # Select the customers whose 'id' is not present in the orders DataFrame's 'customerId' column.
    df = customers[~customers["id"].isin(orders["customerId"])]

    # Build a DataFrame that only contains the 'name' column and rename it as 'Customers'.
    df = df[["name"]].rename(columns={"name": "Customers"})

    return df

Complexity

Time
O(n log n)(typical)
Space · auxiliary
O(n)

Related problems

Frequently asked questions

How hard is LeetCode 183. Customers Who Never Order?

LeetCode 183. Customers Who Never Order is rated Easy on LeetCode.

What topics does LeetCode 183. Customers Who Never Order cover?

LeetCode 183. Customers Who Never Order is tagged Database on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.