Project Employees III
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.
rows = [(1,1,3), (1,3,3), (1,2,2), (2,1,3)][(1,1), (1,3), (2,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;
}
Explanation
For each project we must return every employee tied for the most experience. Because there can be ties, we use a clean two-pass approach instead of trying to track winners on the fly.
The first pass builds a hash map best where best[pid] is the maximum experience years seen for that project. We update it whenever a row beats the current max.
The second pass scans the rows again and keeps every (pid, eid) whose years exactly equals best[pid]. Comparing for equality is what lets multiple tied employees all make the cut.
Example: [(1,1,3), (1,3,3), (1,2,2), (2,1,3)]. Project 1's max is 3, so employees 1 and 3 (both 3 years) are kept while employee 2 (2 years) is dropped. Project 2's max is 3 → only employee 1.
The result is [(1,1), (1,3), (2,1)] — every project's top performers, ties included.