EasyNo. 0586

Customer Placing the Largest Number of Orders — LeetCode 586 Python Solution

Topics
Database
Reading time
2 min

The problem

Find the customer who placed the most orders and report their customer number. The test data guarantees exactly one customer holds the record. The Orders table has one row per order: order_number (int, the primary key) and customer_number (int, the customer who placed that order).

Example

Example
Orders table:

| order_number | customer_number |
| ------------ | --------------- |
| 101          | 7               |
| 102          | 4               |
| 103          | 7               |
| 104          | 9               |
| 105          | 7               |

Result:

| customer_number |
| --------------- |
| 7               |

Customer 7 placed three orders while customers 4 and 9 placed one each, so 7 is the answer.

Python solution

PythonSolution
import pandas as pd

def customer_with_most_orders(orders: pd.DataFrame) -> pd.DataFrame:
    counts = orders.groupby('customer_number').size()
    max_cnt = counts.max()
    winner = counts[counts == max_cnt].index.min()
    return pd.DataFrame({'customer_number': [int(winner)]})

Complexity

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

Related problems

Related problems
No.ProblemDifficulty
0585Investments in 2016Medium
0584Find Customer RefereeEasy
0577Employee BonusEasy
0595Big CountriesEasy
0596Classes With at Least 5 StudentsEasy
0175Combine Two TablesEasy

Frequently asked questions

How hard is LeetCode 586. Customer Placing the Largest Number of Orders?

LeetCode 586. Customer Placing the Largest Number of Orders is rated Easy on LeetCode.

What topics does LeetCode 586. Customer Placing the Largest Number of Orders cover?

LeetCode 586. Customer Placing the Largest Number of Orders 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.