Problem 1418

Abstract / Summary

Show a table listing each customer and the food they ordered, counting how many times each food was ordered by each customer.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1418.py

class Solution:
    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
        # distinct meals
        meals = set()
        for o in orders:
            meals.add(o[2])

        all = {}
        for o in orders:
            table = int(o[1])
            food  = o[2]
            if table not in all:
                all[table] = {}
                for m in meals:
                    all[table][m] = 0
            all[table][food] += 1

        yield [ "Table" ] + sorted(meals)
        for a in sorted(all):
            row = [ str(a) ]
            for m in sorted(meals):
                row.append(str(all[a][m]))
            yield row
23 lines | 681 bytes | submitted November 1, 2023 | GitHub   5% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 76% (50k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • Ordered Set
  • Sorting
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution.displayTable method transforms a list of restaurant orders into a display table that enumerates how many of each food item were ordered at each table. The function builds a collection of distinct meals, aggregates counts per table, and then yields rows that form the final table. The use of a generator (yield) allows the caller to consume rows one at a time, which can be advantageous when the result is large.

Distinct Meal Collection

The first logical block extracts every unique meal name from the input.

meals = set()
for o in orders:
    meals.add(o[2])

By employing a set, duplicate meal names are automatically eliminated, guaranteeing that each meal appears only once in the header row. This step also prepares the data for deterministic ordering later on.

Table-wise Count Aggregation

The second block constructs a nested dictionary that maps each table number to a dictionary of meal counts.

all = {}
for o in orders:
    table = int(o[1])
    food  = o[2]
    if table not in all:
        all[table] = {}
        for m in meals:
            all[table][m] = 0
    all[table][food] += 1

When a new table identifier is encountered, the code creates an entry for that table and pre-populates the inner dictionary with a zero count for every distinct meal. This pre-initialization ensures that later lookups for any meal at any table will succeed without additional existence checks. The subsequent increment updates the count for the specific food item.

Edge Cases Addressed

  • Orders list is empty - The meals set remains empty, and the outer dictionary all stays empty. The generator will still produce a header row containing only "Table" and then terminate, handling the empty input gracefully.
  • Tables with no orders for a particular meal - Because each table’s inner dictionary is seeded with zero for every meal, the output row will contain "0" for meals that were never ordered at that table.
  • Multiple orders for the same table and meal - The increment operation (+= 1) correctly accumulates the total count across all matching entries.
  • Non-sequential table numbers - Table identifiers are stored as integers and later iterated in sorted order, so gaps in numbering do not affect correctness.

Header Row Generation

The header row is produced first, combining the literal "Table" label with the alphabetically sorted list of distinct meals.

yield [ "Table" ] + sorted(meals)

Sorting the meal names guarantees a consistent column order regardless of the order in which they appeared in the input.

Data Row Generation

For each table, sorted in ascending numeric order, a row is assembled.

for a in sorted(all):
    row = [ str(a) ]
    for m in sorted(meals):
        row.append(str(all[a][m]))
    yield row

The table number is converted to a string to match the expected output type. The inner loop iterates over the same sorted meal list used for the header, pulling the pre-computed count for each meal from the table’s dictionary. Converting each count to a string aligns the data type across the entire table.

Edge Cases Addressed

  • Tables appearing out of order in the input - Sorting all keys ensures rows are emitted in numeric order, independent of input ordering.
  • Meals that never appear in any order - If the orders list is empty, meals is empty, and the header consists solely of "Table". The row-generation loop does not execute because all is empty, resulting in a correct minimal table.

Performance Optimizations

The algorithm incorporates several choices that reduce overhead:

  • Using a set for meal collection eliminates the need for explicit duplicate checks, providing O(1) average-time insertion.
  • Pre-initializing each table’s inner dictionary with zero counts avoids repeated conditional checks when accessing counts during row construction.
  • Sorting is performed only twice: once for the header meal list and once for the table identifiers. The sorted lists are reused for both header and data rows, preventing redundant sorting operations.
  • Emitting rows via yield creates a lazy sequence, which can lower memory consumption when the caller processes rows incrementally rather than materializing the entire table at once.

Overall, the method builds the required display table in a single pass over the input for aggregation, followed by deterministic ordering steps that are bounded by the number of distinct tables and meals.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a busy restaurant kitchen where waiters keep bringing in scraps of paper with food orders for different tables. This code acts like a very organized robot chef. First, it looks at all the scraps of paper to see what special items are being cooked and remembers every single type of meal.

Next, it creates a digital notebook where each page belongs to a specific table. It goes through every scrap of paper again. When it finds a table number, it opens the right page in the notebook and adds a little tally mark to the food the people sitting there ordered.

After all the orders are sorted into the notebook, the robot gets ready to print a big, tidy display table. It writes the word Table at the top of the first column, followed by a list of all the different meals in alphabetical order across the top row. Then, it carefully goes through its notebook, table by table, and writes down the table number followed by how many times each meal was ordered, filling in all the squares perfectly.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 5.5 | μ = 5.42 | σ = 1.57

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++
leetcode.ca C++ Java Python Go TS
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
varunu28 Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
varunu28 Java
wisdompeak C++
22 links | 13 authors | 7 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

6 solutions   November 1, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality