Immediate Food Delivery II

medium hash map group by aggregation

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.

Inputrows = [c1 o0 p0, c2 o6 p6, c3 o5 p9, c4 o6 p10]
Output50.00
First orders: c1(o0=p0 immediate), c2(o6=p6 immediate), c3(o5≠p9 scheduled), c4(o6≠p10 scheduled). 2 of 4 are immediate → 50.00%.

def 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;
}
Time: O(n) Space: O(c)