LeetCode 1418: Display Table of Food Orders in a Restaurant
Problem Description
Explanation
To solve this problem, we need to iterate over the orders and create a mapping of table numbers to the count of each food item ordered by that table. We can achieve this by using a hashmap where the key is the table number and the value is another hashmap that maps food items to their count.
- Create a hashmap
tableOrders
to store the mapping of table numbers to the count of each food item ordered. - Iterate through the orders and update the
tableOrders
hashmap accordingly. - Extract the unique food items from all orders and sort them in alphabetical order.
- Create the result table, with the first row containing the food items in alphabetical order.
- Iterate through the table numbers in sorted order and populate the counts of food items for each table accordingly.
Time complexity: O(n * m) where n is the number of orders and m is the average number of unique food items per order. Space complexity: O(n * m) for the hashmap storing the table orders. Java:
Solutions
class Solution {
public List<List<String>> displayTable(List<List<String>> orders) {
Map<Integer, Map<String, Integer>> tableOrders = new TreeMap<>();
Set<String> foodItems = new TreeSet<>();
for (List<String> order : orders) {
int tableNum = Integer.parseInt(order.get(1));
String foodItem = order.get(2);
foodItems.add(foodItem);
tableOrders.putIfAbsent(tableNum, new TreeMap<>());
Map<String, Integer> foodCount = tableOrders.get(tableNum);
foodCount.put(foodItem, foodCount.getOrDefault(foodItem, 0) + 1);
}
List<List<String>> result = new ArrayList<>();
List<String> header = new ArrayList<>();
header.add("Table");
header.addAll(foodItems);
result.add(header);
for (Map.Entry<Integer, Map<String, Integer>> entry : tableOrders.entrySet()) {
List<String> row = new ArrayList<>();
row.add(String.valueOf(entry.getKey()));
for (String foodItem : foodItems) {
row.add(String.valueOf(entry.getValue().getOrDefault(foodItem, 0)));
}
result.add(row);
}
return result;
}
}
Loading editor...