Project Employees III

medium hash map group by max with ties

Problem

You are given rows of (project_id, employee_id, experience_years). For each project, return the employee(s) with the most experience years on that project. If several employees tie for the maximum within a project, return all of them. The algorithmic core is a group-by-max followed by a pass that keeps every row equal to its group's maximum.

Inputrows = [(1,1,3), (1,3,3), (1,2,2), (2,1,3)]
Output[(1,1), (1,3), (2,1)]
Project 1 has max experience 3 — employees 1 and 3 both tie. Project 2's max is 3 — only employee 1.

def project_employees_iii(rows):
    best = {}
    for pid, eid, years in rows:
        if pid not in best or years > best[pid]:
            best[pid] = years
    ans = []
    for pid, eid, years in rows:
        if years == best[pid]:
            ans.append((pid, eid))
    return ans
function projectEmployeesIII(rows) {
  const best = new Map();
  for (const [pid, eid, years] of rows) {
    if (!best.has(pid) || years > best.get(pid)) best.set(pid, years);
  }
  const ans = [];
  for (const [pid, eid, years] of rows) {
    if (years === best.get(pid)) ans.push([pid, eid]);
  }
  return ans;
}
class Solution {
    public List<int[]> projectEmployeesIII(int[][] rows) {
        Map<Integer, Integer> best = new HashMap<>();
        for (int[] r : rows) {
            best.merge(r[0], r[2], Math::max);
        }
        List<int[]> ans = new ArrayList<>();
        for (int[] r : rows) {
            if (r[2] == best.get(r[0])) ans.add(new int[]{ r[0], r[1] });
        }
        return ans;
    }
}
vector<pair<int,int>> projectEmployeesIII(vector<array<int,3>>& rows) {
    unordered_map<int, int> best;
    for (auto& r : rows) {
        if (!best.count(r[0]) || r[2] > best[r[0]]) best[r[0]] = r[2];
    }
    vector<pair<int,int>> ans;
    for (auto& r : rows) {
        if (r[2] == best[r[0]]) ans.push_back({ r[0], r[1] });
    }
    return ans;
}
Time: O(n) Space: O(p)