Display Table of Food Orders in a Restaurant solution and explanation
5 more videos on this problem
1418. Display Table of Food Orders in a RestaurantLeetcode and Interview Question · 11:15 · 1K views
Display Table of Food Orders in a Restaurant (Leetcode 1418)Coding Interviews · 14:49 · 884 views
Display Table of Food Orders in a Restaurant || Weekly Contest 185 || leetcode 1418 || c++ solutioncode Explainer · 10:33 · 793 views
1418. Display Table of Food Orders in a Restaurant - Javascript - Time: O(n) Space: O(n) - LeetcodeAaron Sadino Coding · 1:07:52 · 103 views
小飞羊 LeetCode 1418 Display Table of Food Orders in a Restaurant 套路得人薪C++Willy小飞羊 DJ · 5:31 · 91 views
LeetCode 1418: Display Table of Food Orders in a RestaurantAlitaCode · 30:37 · 13 views
The problem
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^4orders[i].length == 31 <= customerNamei.length, foodItemi.length <= 20customerNameiandfoodItemiconsist of lowercase and uppercase English letters and the space character.tableNumberiis a valid integer between1and500.
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.
from collections import defaultdict
def displayTable(orders):
food_items = set()
table_orders = defaultdict(lambda: defaultdict(int))
for name, table, food in orders:
food_items.add(food)
table_orders[table][food] += 1
sorted_food_items = sorted(food_items)
result = [['Table'] + sorted_food_items]
for table in sorted(table_orders.keys(), key=int):
row = [table] + [str(table_orders[table][food]) for food in sorted_food_items]
result.append(row)
return result
orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]]
print(displayTable(orders))import java.util.*;
public class RestaurantDisplay {
public List<List<String>> displayTable(List<List<String>> orders) {
Set<String> foodItems = new TreeSet<>();
Map<String, Map<String, Integer>> tableOrders = new TreeMap<>();
for (List<String> order : orders) {
String table = order.get(1);
String food = order.get(2);
foodItems.add(food);
tableOrders.putIfAbsent(table, new HashMap<>());
tableOrders.get(table).merge(food, 1, Integer::sum);
}
List<String> header = new ArrayList<>(foodItems);
header.add(0, "Table");
List<List<String>> result = new ArrayList<>();
result.add(header);
for (Map.Entry<String, Map<String, Integer>> entry : tableOrders.entrySet()) {
List<String> row = new ArrayList<>();
row.add(entry.getKey());
for (String food : foodItems) {
row.add(String.valueOf(entry.getValue().getOrDefault(food, 0)));
}
result.add(row);
}
return result;
}
public static void main(String[] args) {
List<List<String>> orders = List.of(
List.of("David","3","Ceviche"),
List.of("Corina","10","Beef Burrito"),
List.of("David","3","Fried Chicken"),
List.of("Carla","5","Water"),
List.of("Carla","5","Ceviche"),
List.of("Rous","3","Ceviche")
);
RestaurantDisplay rd = new RestaurantDisplay();
System.out.println(rd.displayTable(orders));
}
}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.
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.
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.
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <string>
using namespace std;
vector<vector<string>> displayTable(vector<vector<string>>& orders) {
set<string> foodItems; // Automatically sorts
map<int, map<string, int>> tableOrders; // Automatically sorts by table
for (const auto& order : orders) {
int table = stoi(order[1]);
const string& food = order[2];
foodItems.insert(food);
tableOrders[table][food]++;
}
vector<string> header = {"Table"};
header.insert(header.end(), foodItems.begin(), foodItems.end());
vector<vector<string>> result;
result.push_back(header);
for (const auto& [table, foods] : tableOrders) {
vector<string> row = {to_string(table)};
for (const auto& food : foodItems) {
row.push_back(to_string(foods.at(food)));
}
result.push_back(row);
}
return result;
}
int main() {
vector<vector<string>> orders = {{"James","12","Fried Chicken"},{"Ratesh","12","Fried Chicken"},{"Amadeus","12","Fried Chicken"},{"Adam","1","Canadian Waffles"},{"Brianna","1","Canadian Waffles"}};
vector<vector<string>> display = displayTable(orders);
for (const auto& row : display) {
for (const auto& item : row) {
cout << item << " ";
}
cout << endl;
}
return 0;
}function displayTable(orders) {
const foodItemsSet = new Set();
const tableOrders = {};
for (const [customer, table, food] of orders) {
if (!tableOrders[table]) tableOrders[table] = {};
if (!tableOrders[table][food]) tableOrders[table][food] = 0;
tableOrders[table][food]++;
foodItemsSet.add(food);
}
const foodItems = [...foodItemsSet].sort();
const sortedTables = Object.keys(tableOrders).sort((a, b) => parseInt(a) - parseInt(b));
const result = [['Table', ...foodItems]];
for (const table of sortedTables) {
const row = [table];
for (const food of foodItems) {
row.push(tableOrders[table][food] ? tableOrders[table][food].toString() : '0');
}
result.push(row);
}
return result;
}
const orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]];
console.log(displayTable(orders));The C++ solution uses a set for food items and two nested maps: one for tables and a second for storing the count of each food. This allows us to automatically sort both table numbers and food items. In the end, we transform map structures into a vector of strings for final output.
Time Complexity: O(nlogn) due to the use of ordered structures (set and map). Space Complexity: O(m + t), where m is the number of distinct food items and t is the number of tables.
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.
function displayTable(orders: string[][]): string[][] {
const tables: Record<number, Record<string, number>> = {};
const items: Set<string> = new Set();
for (const [_, table, foodItem] of orders) {
const t = +table;
if (!tables[t]) {
tables[t] = {};
}
if (!tables[t][foodItem]) {
tables[t][foodItem] = 0;
}
tables[t][foodItem]++;
items.add(foodItem);
}
const sortedItems = Array.from(items).sort();
const ans: string[][] = [];
const header: string[] = ['Table', ...sortedItems];
ans.push(header);
const sortedTableNumbers = Object.keys(tables)
.map(Number)
.sort((a, b) => a - b);
for (const table of sortedTableNumbers) {
const row: string[] = [table.toString()];
for (const item of sortedItems) {
row.push((tables[table][item] || 0).toString());
}
ans.push(row);
}
return ans;
}func displayTable(orders [][]string) [][]string {
tables := make(map[int]map[string]int)
items := make(map[string]bool)
for _, order := range orders {
table, _ := strconv.Atoi(order[1])
foodItem := order[2]
if tables[table] == nil {
tables[table] = make(map[string]int)
}
tables[table][foodItem]++
items[foodItem] = true
}
sortedItems := make([]string, 0, len(items))
for item := range items {
sortedItems = append(sortedItems, item)
}
sort.Strings(sortedItems)
ans := [][]string{}
header := append([]string{"Table"}, sortedItems...)
ans = append(ans, header)
tableNums := make([]int, 0, len(tables))
for table := range tables {
tableNums = append(tableNums, table)
}
sort.Ints(tableNums)
for _, table := range tableNums {
row := []string{strconv.Itoa(table)}
for _, item := range sortedItems {
count := tables[table][item]
row = append(row, strconv.Itoa(count))
}
ans = append(ans, row)
}
return ans
}Complexity comparison
| Approach | Complexity |
|---|---|
| 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) due to the use of ordered structures (set and map). Space Complexity: O(m + t), where m is the number of distinct food items and t is the number of tables. |
| Hash Table + Sorting | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Dictionary for Table and Food Mapping | O(n log f + t log t) | O(t * f) | General solution; easiest to implement using hash maps and sets |
| 2D Array with Index Mapping | O(n + f log f + t log t) | O(t * f) | When you want direct indexed updates instead of nested maps |
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.
