Reformat Department Table

easy pivot group by hash map

Problem

A Department table has rows (id, revenue, month) where each row is one department's revenue in one month. Reformat it so there is exactly one row per department id, with a separate column for each month's revenue: Jan_Revenue, Feb_Revenue, …, Dec_Revenue. A month missing for a department becomes null.

Input(1, 8000, Jan), (2, 9000, Jan), (3, 10000, Feb), (1, 7000, Feb), (1, 6000, Mar)
Outputid=1 → Jan 8000, Feb 7000, Mar 6000; id=2 → Jan 9000; id=3 → Feb 10000
Each (id, month) cell is filled by the matching input row; absent months stay null.

MONTHS = ["Jan","Feb","Mar","Apr","May","Jun",
          "Jul","Aug","Sep","Oct","Nov","Dec"]

def reformat(rows):
    table = {}
    for id, revenue, month in rows:
        row = table.setdefault(id, {})
        row[month] = revenue
    out = []
    for id in sorted(table):
        out.append([id] + [table[id].get(m) for m in MONTHS])
    return out
const MONTHS = ["Jan","Feb","Mar","Apr","May","Jun",
                "Jul","Aug","Sep","Oct","Nov","Dec"];

function reformat(rows) {
  const table = new Map();
  for (const [id, revenue, month] of rows) {
    if (!table.has(id)) table.set(id, {});
    table.get(id)[month] = revenue;
  }
  const out = [];
  for (const id of [...table.keys()].sort((a, b) => a - b)) {
    const r = table.get(id);
    out.push([id, ...MONTHS.map(m => (m in r ? r[m] : null))]);
  }
  return out;
}
class Solution {
    static final String[] MONTHS = {"Jan","Feb","Mar","Apr","May","Jun",
                                    "Jul","Aug","Sep","Oct","Nov","Dec"};
    public List<long[]> reformat(int[][] rows) {
        Map<Integer, Map<String, Long>> table = new TreeMap<>();
        for (int[] r : rows) {           // r = {id, revenue, monthIdx}
            table.computeIfAbsent(r[0], k -> new HashMap<>())
                 .put(MONTHS[r[2]], (long) r[1]);
        }
        List<long[]> out = new ArrayList<>();
        for (var e : table.entrySet()) {
            long[] row = new long[13];
            row[0] = e.getKey();
            for (int m = 0; m < 12; m++)
                row[m + 1] = e.getValue().getOrDefault(MONTHS[m], -1L);
            out.add(row);
        }
        return out;
    }
}
const vector<string> MONTHS = {"Jan","Feb","Mar","Apr","May","Jun",
                               "Jul","Aug","Sep","Oct","Nov","Dec"};

map<int, unordered_map<string, long>> reformat(vector<tuple<int,long,string>>& rows) {
    map<int, unordered_map<string, long>> table;
    for (auto& [id, revenue, month] : rows) {
        table[id][month] = revenue;   // group by id, scatter by month
    }
    return table;                     // ordered by id; missing months absent
}
Time: O(n + k log k) Space: O(k)