Skip to main content

Display Table of Food Orders in a Restaurant - Solution & Explanation

MediumArrayHash TableStringSorting14 min readAsked at: Jpmorgan, Nordstrom
Practice this problem

Problem Statement

Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders.

Return the restaurant's “display table. The “display table” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.

 

Example 1:

Input: orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]]
Output: [["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]] 
Explanation:
The displaying table looks like:
Table,Beef Burrito,Ceviche,Fried Chicken,Water
3    ,0           ,2      ,1            ,0
5    ,0           ,1      ,0            ,1
10   ,1           ,0      ,0            ,0
For the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche".
For the table 5: Carla orders "Water" and "Ceviche".
For the table 10: Corina orders "Beef Burrito". 

Example 2:

Input: orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]]
Output: [["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]] 
Explanation: 
For the table 1: Adam and Brianna order "Canadian Waffles".
For the table 12: James, Ratesh and Amadeus order "Fried Chicken".

Example 3:

Input: orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]]
Output: [["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]]

 

Constraints:

  • 1 <= orders.length <= 5 * 10^4
  • orders[i].length == 3
  • 1 <= customerNamei.length, foodItemi.length <= 20
  • customerNamei and foodItemi consist of lowercase and uppercase English letters and the space character.
  • tableNumberi is a valid integer between 1 and 500.

Approach Overview

Problem Overview: You receive a list of restaurant orders where each record contains a customer name, table number, and food item. The goal is to generate a display table showing how many of each food item every table ordered. Food names must appear in alphabetical order and table numbers must appear in numeric order.

Approach 1: Using Dictionary for Table and Food Mapping (O(n log f + t log t) time, O(t * f) space)

The core idea is to aggregate counts using a nested hash map. Iterate through the orders and maintain a mapping like table -> {food -> count}. At the same time, track all unique food items using a set so the header row can be sorted alphabetically. After processing all orders, sort the food names and table numbers. Then construct the final matrix row by row by reading counts from the hash map, defaulting to 0 when a table never ordered a specific food. Hash lookups make updates constant time, which keeps the counting step efficient. This approach relies heavily on Hash Table lookups and simple Array construction.

Approach 2: Using 2D Array and Index Mapping (O(n + f log f + t log t) time, O(t * f) space)

This version precomputes indexes for both foods and tables and stores counts directly inside a 2D grid. First collect all unique foods and sort them alphabetically. Assign each food a column index using a dictionary. Do the same for tables (sorted numerically). Then allocate a 2D array where rows represent tables and columns represent foods. Iterate through the orders and increment the corresponding cell using the precomputed indexes. Finally prepend the header row and convert counts to strings for the output. This approach avoids nested maps and instead relies on direct index access, which can be slightly faster in languages like C++ or JavaScript. Sorting still uses standard Sorting operations to maintain the required output order.

Recommended for interviews: The dictionary mapping approach is the most common explanation because it mirrors the natural grouping of table -> food counts. It clearly demonstrates proficiency with hash tables and aggregation problems. The 2D array version is equally valid and sometimes preferred when you want tighter control over memory layout or faster indexed updates.

Approach 1: Using Dictionary for Table and Food Mapping

This approach involves using a dictionary to map each table to another dictionary that represents the number of each food item ordered. Two steps are crucial: maintain a set to gather all unique food items (sorted for the header) and populate a nested dictionary mapping tables to their respective food items and their counts.

We first collect all unique food items and map each table number to a dictionary of food items and their respective counts using a defaultdict. After processing the orders, we sort the food items for the header. Then, we sort table numbers and construct each row by mapping each food item to its count on each table, filling zero as default.

Code

Python

Java

Complexity

Time Complexity: O(nlogn), where n is the number of orders (for sorting and iterating through orders). Space Complexity: O(m + t), where m is the number of distinct food items and t is the number of tables.

Try this approach in the editor →

Approach 2: Using 2D Array and Index Mapping

This approach involves creating a mapping of food items to indices in a 2D array, allowing direct access via array indices for quick updates. This approach first maps food items to indices, constructs a result matrix, and populates it using the given orders. Sorting for headers and rows is carried out separately.

JavaScript code uses a Set to gather unique food items and a plain object as a dictionary to count food orders by table. After each order is processed, it sorts the food items and tables. Finally, it builds the resulting display table by iterating through the sorted structure and filling it with counts mapped to indices.

Code

JavaScript

C++

Complexity

Time Complexity: O(nlogn), primarily due to sorting operations. Space Complexity: O(m + t), for storing food items and table orders.

Try this approach in the editor →

Approach 3: Hash Table + Sorting

We can use a hash table tables to store the dishes ordered at each table, and a set items to store all the dishes.

Traverse orders, storing the dishes ordered at each table in tables and items.

Then we sort items to get sortedItems.

Next, we construct the answer array ans. First, add the header row header to ans. Then, traverse the sorted tables. For each table, use a counter cnt to count the number of each dish, then construct a row row and add it to ans.

Finally, return ans.

The time complexity is O(n + m times log m + k times log k + m times k), and the space complexity is O(n + m + k). Here, n is the length of the array orders, while m and k represent the number of dish types and the number of tables, respectively.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Using Dictionary for Table and Food Mapping

Time Complexity: O(nlogn), where n is the number of orders (for sorting and iterating through orders). Space Complexity: O(m + t), where m is the number of distinct food items and t is the number of tables.

Using 2D Array and Index Mapping

Time Complexity: O(nlogn), primarily due to sorting operations. Space Complexity: O(m + t), for storing food items and table orders.

Hash Table + Sorting—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Dictionary for Table and Food MappingO(n log f + t log t)O(t * f)General solution; easiest to implement using hash maps and sets
2D Array with Index MappingO(n + f log f + t log t)O(t * f)When you want direct indexed updates instead of nested maps

Video Solution

1418. Display Table of Food Orders in a Restaurant • Leetcode and Interview Question • 1,166 views views

Watch 5 more video solutions →

Frequently Asked Questions

Is Display Table of Food Orders in a Restaurant easy or hard?
The problem is rated Medium because the logic combines multiple steps: grouping data, tracking unique items, sorting them, and constructing a matrix output. The individual operations are straightforward but coordinating them correctly requires careful indexing and data structure usage.
Display Table of Food Orders in a Restaurant Python/Java solution
Python solutions typically use a defaultdict or dictionary of dictionaries to store counts and a set for food names. Java implementations often use HashMap<Integer, Map<String, Integer>> combined with a TreeSet or sorted list for foods. Both versions build the final table after sorting foods and table numbers.
How to solve Display Table of Food Orders in a Restaurant in O(n)?
Pure O(n) is difficult because the output requires foods to be alphabetically sorted and tables numerically sorted. However the counting step itself is O(n) using a hash map. After aggregation, sorting the unique foods and tables produces the final ordered display table.
What is the best approach for Display Table of Food Orders in a Restaurant?
The most common approach uses a hash map that maps table numbers to another map of food items and counts. While processing each order you increment the count for that table and food. After collecting all data, sort the food names alphabetically and table numbers numerically, then build the result table. This approach runs in roughly O(n log f + t log t) time.
Is Display Table of Food Orders in a Restaurant asked at Google/Amazon/Meta?
This problem represents a common interview pattern involving hash map aggregation and sorting structured results. Variants of grouping and counting records by key appear in interviews at companies like Amazon, Google, and Meta, especially for data processing style questions.
What data structure is used in Display Table of Food Orders in a Restaurant?
The main data structures are hash tables (dictionaries) to count food items per table and sets to track unique food names. Some implementations also use a 2D array to store counts once indexes for tables and foods are determined. Sorting structures ensure the final output order.
What is the time complexity of Display Table of Food Orders in a Restaurant?
Counting orders is O(n) using hash table updates. Additional sorting of food names and table numbers adds O(f log f + t log t). Overall complexity is typically expressed as O(n + f log f + t log t) or O(n log f + t log t) depending on implementation details.

Ready to solve this problem?

Practice Display Table of Food Orders in a Restaurant with our built-in code editor and test cases.

Practice on FleetCode