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

EasyDatabase
Problem
#586
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

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

Python
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

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

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.

Get Stealth Interview