Display Table of Food Orders in a Restaurant — LeetCode 1418 Python Solution

MediumArrayHash TableStringOrdered SetSorting
Problem
#1418
Pattern
Sorting
Reading time
3 min

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.

Example

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:

Python solution

Python
class Solution:
    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
        tables = defaultdict(list)
        items = set()
        for _, table, foodItem in orders:
            tables[int(table)].append(foodItem)
            items.add(foodItem)
        sorted_items = sorted(items)
        ans = [["Table"] + sorted_items]
        for table in sorted(tables):
            cnt = Counter(tables[table])
            row = [str(table)] + [str(cnt[item]) for item in sorted_items]
            ans.append(row)
        return ans

Complexity

MeasureComplexity
TimeO(n + m \times \log m + k \times \log k + m \times k)
SpaceO(n + m + k) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1418. Display Table of Food Orders in a Restaurant is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1418. Display Table of Food Orders in a Restaurant?
LeetCode 1418. Display Table of Food Orders in a Restaurant is rated Medium on LeetCode.
What is the time complexity of LeetCode 1418. Display Table of Food Orders in a Restaurant?
The Python solution on this page runs in O(n + m \times \log m + k \times \log k + m \times k).
What is the space complexity of LeetCode 1418. Display Table of Food Orders in a Restaurant?
The Python solution on this page uses O(n + m + k) auxiliary space.
What topics does LeetCode 1418. Display Table of Food Orders in a Restaurant cover?
LeetCode 1418. Display Table of Food Orders in a Restaurant is tagged Array, Hash Table, String, Ordered Set and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview