Immediate Food Delivery II
Problem
Each delivery has a customer_id, an order_date, and a customer_pref_delivery_date. An order is immediate if the preferred date equals the order date; otherwise it is scheduled. A customer's first order is the one with the earliest order date. Return the percentage of immediate orders among the first orders of all customers, rounded to two decimals.
rows = [c1 o0 p0, c2 o6 p6, c3 o5 p9, c4 o6 p10]50.00def immediate_percentage(rows):
first = {}
for cust, order, pref in rows:
if cust not in first or order < first[cust][0]:
first[cust] = (order, pref)
total = len(first)
immediate = sum(1 for o, p in first.values() if o == p)
return round(immediate * 100 / total, 2)
function immediatePercentage(rows) {
const first = new Map();
for (const [cust, order, pref] of rows) {
if (!first.has(cust) || order < first.get(cust)[0]) {
first.set(cust, [order, pref]);
}
}
const total = first.size;
let immediate = 0;
for (const [o, p] of first.values()) if (o === p) immediate++;
return Math.round(immediate * 10000 / total) / 100;
}
double immediatePercentage(int[][] rows) {
Map<Integer, int[]> first = new HashMap<>();
for (int[] r : rows) {
int cust = r[0], order = r[1], pref = r[2];
if (!first.containsKey(cust) || order < first.get(cust)[0]) {
first.put(cust, new int[]{ order, pref });
}
}
int total = first.size(), immediate = 0;
for (int[] f : first.values()) if (f[0] == f[1]) immediate++;
return Math.round(immediate * 10000.0 / total) / 100.0;
}
double immediatePercentage(vector<array<int,3>>& rows) {
unordered_map<int, pair<int,int>> first;
for (auto& r : rows) {
int cust = r[0], order = r[1], pref = r[2];
if (!first.count(cust) || order < first[cust].first)
first[cust] = { order, pref };
}
int total = first.size(), immediate = 0;
for (auto& kv : first) if (kv.second.first == kv.second.second) immediate++;
return round(immediate * 10000.0 / total) / 100.0;
}
Explanation
We only care about each customer's first order — the one with the earliest order date. So as we scan the rows, we keep a hash map from customer_id to their earliest order seen so far, replacing the stored value whenever a smaller order date shows up.
The update rule is if cust not in first or order < first[cust][0], which guarantees the map ends up holding exactly the first order per customer regardless of input order.
Once the map is built, every entry is a first order. An order is immediate when its preferred date equals its order date, so we just count how many stored pairs have o == p.
Example: rows c1(o0,p0), c2(o6,p6), c3(o5,p9), c4(o6,p10). First orders give two immediates (c1, c2) out of four customers.
The answer is immediate * 100 / total rounded to two decimals — here 2 * 100 / 4 = 50.00.