Talentd
FleetCode
Make and follow sheets.Sign in

Customer Placing the Largest Number of Orders solution and explanation

EasyDatabase5 min read64.6% acceptanceUpdated 9 Apr 2026
LeetCode Interview SQL Question with Detailed Explanation | Practice SQL | LeetCode 586Everyday Data Science · 9:02 · 23K viewsWatch on YouTube
9 more videos on this problem
  1. LeetCode Interview SQL Question with Detailed Explanation | Practice SQL | LeetCode 586Everyday Data Science · 9:02 · 23K views
  2. LeetCode 586: Customer Placing the Largest Number of Orders [SQL]Frederik Müller · 4:52 · 5K views
  3. LeetCode 586 - Customer Placing the Largest Number of Orders WalkthroughBig Tech Mindset · 2:43 · 862 views
  4. Customer Placing the Largest Number of Orders - Leetcode 586 | Week 4 | Qs 14 | SQLThe Big Data Show · 5:27 · 834 views
  5. LeetCode 586 Customer Placing the Largest Number of Orders (Python and SQL) [Easy]Ryan & Matt Data Science · 6:30 · 537 views
  6. LeetCode SQL Easy - 586 | Customer Placing the Largest Number of OrdersTaniya Saini · 6:54 · 401 views
  7. Leetcode SQL 586.Customers Placing The Largest Number Of Orders #leetcodesolutionMoody Mansi😉 · 4:50 · 173 views
  8. Leetcode 586 Customer Placing the Largest Number of Orders Oracle Query ExplainedAlgorithmicIQ · 10:14 · 151 views
  9. 586. Customer Placing the Largest Number of Orders (LeetCode, SQL)hakunamatasq · 2:23 · 151 views
  10. 586. Customer Placing The Largest Number of Orders | LeetCode | SQL | Solution | Interview ProblemData Alchemist · 3:48 · 139 views

The problem

Table: Orders

+-----------------+----------+
| Column Name     | Type     |
+-----------------+----------+
| order_number    | int      |
| customer_number | int      |
+-----------------+----------+
order_number is the primary key (column with unique values) for this table.
This table contains information about the order ID and the customer ID.

Write a solution to find the customer_number for the customer who has placed the largest number of orders.

The test cases are generated so that exactly one customer will have placed more orders than any other customer.

The result format is in the following example.

Example 1:

Input: 
Orders table:
+--------------+-----------------+
| order_number | customer_number |
+--------------+-----------------+
| 1            | 1               |
| 2            | 2               |
| 3            | 3               |
| 4            | 3               |
+--------------+-----------------+
Output: 
+-----------------+
| customer_number |
+-----------------+
| 3               |
+-----------------+
Explanation: 
The customer with number 3 has two orders, which is greater than either customer 1 or 2 because each of them only has one order. 
So the result is customer_number 3.

Follow up: What if more than one customer has the largest number of orders, can you find all the customer_number in this case?

Approach overview

Problem Overview: The Orders table stores customer purchases with a customer_number. The task is to return the customer who placed the highest number of orders. If one customer appears most frequently, that customer’s ID should be returned.

Approach 1: SQL GROUP BY with MAX Aggregation (Time: O(n), Space: O(k))

This approach relies on SQL aggregation. First group all rows by customer_number using GROUP BY. Then compute the order count for each customer with COUNT(*). The customer with the maximum count can be retrieved using a subquery with MAX or by sorting the grouped results and selecting the top record.

The key insight: aggregation compresses repeated rows into frequency counts directly inside the database engine. Instead of scanning repeatedly, the database builds grouped buckets for each customer. The final step simply returns the customer whose count equals the maximum value.

This is the most natural solution for a database problem because relational systems are optimized for grouping and aggregation operations. Complexity is linear relative to the number of rows O(n), while space is O(k) where k is the number of unique customers.

Approach 2: Manual Aggregation with Data Structures (Time: O(n), Space: O(k))

If the data is processed outside the database (for example in Python or Java), you can simulate SQL aggregation using a hash map. Iterate through every order and maintain a frequency counter where the key is customer_number and the value is the number of orders placed by that customer.

During the iteration, update the count for each customer and track the maximum frequency seen so far. After processing all rows, return the customer associated with the highest count.

This approach mirrors SQL GROUP BY behavior but uses a hash-based frequency table. Each lookup and update is constant time on average, so the full scan runs in O(n) time. Memory usage grows with the number of distinct customers, resulting in O(k) space. This technique is common in hash table problems and is useful when processing query results in application code rather than directly in SQL.

Recommended for interviews: The SQL GROUP BY approach is the expected answer because the problem is designed around database querying. Interviewers want to see correct use of aggregation functions and filtering with MAX. Understanding the manual hash-map version still matters since it shows you understand how grouping works internally rather than relying only on SQL syntax.

Approach 1: Approach 1: Using SQL Group By and Max

This approach leverages the SQL capabilities of grouping and aggregation to solve the problem efficiently.

First, we perform a GROUP BY operation on the customer_number to count the number of orders per customer. Then, we use ORDER BY in descending order and LIMIT 1 to retrieve only the customer with the maximum count of orders.

import sqlite3

def get_largest_order_customer():
    connection = sqlite3.connect(':memory:')
    cursor = connection.cursor()
    # Assumed table creation and data insertion here.
    query = '''
    SELECT customer_number
    FROM Orders
    GROUP BY customer_number
    ORDER BY COUNT(order_number) DESC
    LIMIT 1;
    '''
    cursor.execute(query)
    result = cursor.fetchone()
    if result:
        print(f"Customer Number: {result[0]}")
    connection.close()

get_largest_order_customer()
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class LargestOrderCustomer {
    public static void main(String[] args) {
        try {
            Connection connection = DriverManager.getConnection("jdbc:sqlite::memory:");
            Statement stmt = connection.createStatement();
            // Assume table creation and data population here.
            String sql = "SELECT customer_number FROM Orders GROUP BY customer_number ORDER BY COUNT(order_number) DESC LIMIT 1;";
            ResultSet rs = stmt.executeQuery(sql);
            if (rs.next()) {
                System.out.println("Customer Number: " + rs.getInt(1));
            }
            rs.close();
            stmt.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
#include <iostream>
#include <sqlite3.h>

void findLargestOrderCustomer(sqlite3* db) {
    sqlite3_stmt* stmt;
    const char* sql = "SELECT customer_number FROM Orders GROUP BY customer_number ORDER BY COUNT(order_number) DESC LIMIT 1;";

    if (sqlite3_prepare_v2(db, sql, -1, &stmt, 0) == SQLITE_OK) {
        if (sqlite3_step(stmt) == SQLITE_ROW) {
            std::cout << "Customer Number: " << sqlite3_column_int(stmt, 0) << std::endl;
        }
        sqlite3_finalize(stmt);
    }
}

int main() {
    sqlite3* db;
    sqlite3_open(":memory:", &db);
    // Assume table creation and data population.
    findLargestOrderCustomer(db);
    sqlite3_close(db);
    return 0;
}
const sqlite3 = require('sqlite3').verbose();

let db = new sqlite3.Database(':memory:');

// Assuming that database and Orders table are already set up
let sql = `SELECT customer_number FROM Orders GROUP BY customer_number ORDER BY COUNT(order_number) DESC LIMIT 1;`;

db.get(sql, [], (err, row) => {
  if (err) {
    throw err;
  }
  console.log(`Customer Number: ${row.customer_number}`);
});

db.close();
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>

/* Function to get the customer with the largest number of orders */
void getLargestOrderCustomer(sqlite3 *db) {
    sqlite3_stmt *stmt;
    const char *sql = "SELECT customer_number FROM Orders GROUP BY customer_number ORDER BY COUNT(order_number) DESC LIMIT 1;";
    
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, 0) == SQLITE_OK) {
        if (sqlite3_step(stmt) == SQLITE_ROW) {
            int customer_number = sqlite3_column_int(stmt, 0);
            printf("Customer Number: %d\n", customer_number);
        }
        sqlite3_finalize(stmt);
    }
}

int main() {
    sqlite3 *db;
    sqlite3_open(":memory:", &db);
    // Assume table creation and data insertion is done here.
    getLargestOrderCustomer(db);
    sqlite3_close(db);
    return 0;
}
using System;
using System.Data.SQLite;

class Program {
    static void Main() {
        using (var connection = new SQLiteConnection("Data Source=:memory:")) {
            connection.Open();
            using (var command = new SQLiteCommand(connection)) {
                // Assumes table and data exist in SQLite.
                command.CommandText = @"
                SELECT customer_number
                FROM Orders
                GROUP BY customer_number
                ORDER BY COUNT(order_number) DESC
                LIMIT 1;";
                using (var reader = command.ExecuteReader()) {
                    if (reader.Read()) {
                        Console.WriteLine("Customer Number: " + reader.GetInt32(0));
                    }
                }
            }
        }
    }
}

This Python snippet connects to an SQLite database, assumes the existence of a table called Orders, and executes a query to find the customer with the most orders using Python's sqlite3 module.

Complexity

Time Complexity: O(n), where n is the total number of orders.
Space Complexity: O(1), since the query operations are handled in the database.

Try this approach in the editor

Approach 2: Approach 2: Manual Aggregation with Data Structures

This approach involves manually iterating over the orders and using a data structure like a hash map (or dictionary) to count the number of orders per customer. Once counted, we can iterate over this collection to find the customer with the maximum orders.

def find_customer_with_most_orders(orders):
    order_count = {}
    # Count orders per customer
    for order in orders:
        customer = order['customer_number']
        if customer in order_count:
            order_count[customer] += 1
        else:
            order_count[customer] = 1
    
    # Find the customer with the maximum orders
    max_orders = -1
    max_customer = -1
    for customer, count in order_count.items():
        if count > max_orders:
            max_orders = count
            max_customer = customer
    
    return max_customer

orders = [{'order_number': 1, 'customer_number': 1}, {'order_number': 2, 'customer_number': 2}, {'order_number': 3, 'customer_number': 3}, {'order_number': 4, 'customer_number': 3}]

print(find_customer_with_most_orders(orders))

This Python code manually counts customer orders using a dictionary to map customer numbers to their respective order counts. Finally, it identifies the customer with the maximum count.

Complexity

Time Complexity: O(n), where n is the number of orders.
Space Complexity: O(m), where m is the number of unique customers.

Try this approach in the editor

Approach 3: Group By + Sorting

We can use GROUP BY to group the data by customer_number, and then sort the groups in descending order by count(1). Finally, we can take the customer_number of the first record as the result.

# Write your MySQL query statement below
SELECT
    customer_number
FROM orders
GROUP BY customer_number
ORDER BY COUNT(1) DESC
LIMIT 1;
Try this approach in the editor

Approach 4: Default Approach

/* Write your T-SQL query statement below */
SELECT TOP 1
    customer_number
FROM
    orders
GROUP BY customer_number
ORDER BY COUNT(customer_number) DESC;
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Using SQL Group By and Max

Time Complexity: O(n), where n is the total number of orders.
Space Complexity: O(1), since the query operations are handled in the database.

Approach 2: Manual Aggregation with Data Structures

Time Complexity: O(n), where n is the number of orders.
Space Complexity: O(m), where m is the number of unique customers.

Group By + Sorting–
Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
SQL GROUP BY with MAXO(n)O(k)Best for database queries where aggregation can be handled directly in SQL
Manual Hash Map AggregationO(n)O(k)Useful when processing rows in application code instead of SQL

Frequently asked questions

Is Customer Placing the Largest Number of Orders easy or hard?

Customer Placing the Largest Number of Orders is classified as an Easy problem. It mainly tests understanding of SQL GROUP BY aggregation and basic counting logic rather than complex algorithms.

Customer Placing the Largest Number of Orders Python/Java solution

In Python or Java, iterate through the orders and maintain a hash map where the key is the customer ID and the value is the order count. After updating counts for each row, return the customer with the maximum frequency. This approach runs in O(n) time with O(k) extra space.

How to solve Customer Placing the Largest Number of Orders in O(n)?

Scan the Orders table once and aggregate counts per customer. In SQL, use GROUP BY customer_number with COUNT(*), then filter using MAX(count). In application code, use a hash map to track frequencies and keep the customer with the highest count while iterating.

What is the best approach for Customer Placing the Largest Number of Orders?

The best approach uses SQL GROUP BY with a MAX aggregation. Group orders by customer_number, count the number of rows per customer, then return the customer whose count equals the maximum. This runs in O(n) time relative to the number of rows and leverages the database engine’s optimized aggregation.

Is Customer Placing the Largest Number of Orders asked at Google/Amazon/Meta?

This problem represents a common database aggregation pattern frequently asked in SQL interviews across companies such as Amazon, Google, and Meta. Variations often test GROUP BY, HAVING, and MAX queries on transaction or order datasets.

What data structure is used in Customer Placing the Largest Number of Orders?

The SQL solution relies on relational aggregation via GROUP BY. When implemented in general-purpose languages, a hash map (dictionary) is typically used to store frequency counts for each customer.

What is the time complexity of Customer Placing the Largest Number of Orders?

The typical SQL aggregation solution runs in O(n) time because each order row is scanned once to compute counts. Space complexity is O(k), where k represents the number of distinct customers stored during grouping.

Comments

Now write it yourselfClose this page and solve Customer Placing the Largest Number of Orders in the editor, without looking.
Practise Customer Placing the Largest Number of Orders