#1418

Display Table of Food Orders in a Restaurant

Medium
ArrayHash TableStringSortingOrdered SetHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

In the optimal solution, we utilize a hash map to efficiently count the occurrences of each food item for each table in a single pass through the orders. This reduces the time complexity significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a hash map to count the frequency of each food item for each table.
  2. 2Step 2: Extract the unique table numbers and food items from the hash map.
  3. 3Step 3: Sort the table numbers and food items, then construct the display table.
solution.py17 lines
1from collections import defaultdict
2
3orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]]
4
5def displayTable(orders):
6    table_food_count = defaultdict(lambda: defaultdict(int))
7    for order in orders:
8        table_food_count[order[1]][order[2]] += 1
9    table_numbers = sorted(table_food_count.keys(), key=int)
10    food_items = sorted(set(item for table in table_food_count.values() for item in table.keys()))
11    display = [["Table"] + food_items]
12    for table in table_numbers:
13        row = [table] + [str(table_food_count[table][food]) for food in food_items]
14        display.append(row)
15    return display
16
17print(displayTable(orders))

Complexity note: The time complexity is O(n log n) due to the sorting of table numbers and food items. The space complexity is O(n) because we use a hash map to store counts, which can grow with the number of unique food items and tables.

  • 1Using a hash map allows for efficient counting of food items per table.
  • 2Sorting is essential for organizing the final output.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.