Approach
Sorting and greedy selection
For Display Table of Food Orders in a Restaurant, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 52 lines of C++ from the credited upstream file 1418.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 9 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<vector<string>> displayTable(vector<vector<string>>& orders) {4 vector<vector<string>> ans{{"Table"}};5 unordered_map<string, int> tableNumberToRowIndex;6 unordered_map<string, int> foodItemToColIndex;7 8 9 for (const vector<string>& order : orders) {10 const string& tableNumber = order[1];11 const string& foodItem = order[2];12 13 tableNumberToRowIndex[tableNumber] = 0;14 foodItemToColIndex[foodItem] = 0;15 }16 for (const auto& [tableNumber, _] : tableNumberToRowIndex)17 ans.push_back({tableNumber});18 for (const auto& [foodItem, _] : foodItemToColIndex)19 ans[0].push_back(foodItem);20 21 22 sort(ans[0].begin() + 1, ans[0].end());23 ranges::sort(ans.begin() + 1, ans.end(), ranges::less{},24 [](const vector<string>& cols) { return stoi(cols[0]); });25 26 27 for (int i = 0; i < tableNumberToRowIndex.size(); ++i)28 tableNumberToRowIndex[ans[i + 1][0]] = i;29 for (int i = 0; i < foodItemToColIndex.size(); ++i)30 foodItemToColIndex[ans[0][i + 1]] = i;31 32 33 vector<vector<int>> count;34 for (int i = 0; i < tableNumberToRowIndex.size(); ++i)35 count.push_back(vector<int>(foodItemToColIndex.size()));36 for (const vector<string>& order : orders) {37 const string& tableNumber = order[1];38 const string& foodItem = order[2];39 const int rowIndex = tableNumberToRowIndex[tableNumber];40 const int colIndex = foodItemToColIndex[foodItem];41 ++count[rowIndex][colIndex];42 }43 44 45 for (int i = 0; i < tableNumberToRowIndex.size(); ++i)46 for (int j = 0; j < foodItemToColIndex.size(); ++j)47 ans[i + 1].push_back(to_string(count[i][j]));48 49 return ans;50 }51};52