Project Employees II
Problem
The Project table links projects to employees through (project_id, employee_id) rows. Report all the projects that have the most employees. Equivalently: count how many employees each project has, find the maximum count, and return every project whose employee count equals that maximum.
rows = [(1,1), (1,2), (1,3), (2,1), (2,4)][1]def projects_with_most_employees(rows):
count = {}
for project_id, _ in rows:
count[project_id] = count.get(project_id, 0) + 1
best = max(count.values())
return [p for p, c in count.items() if c == best]
function projectsWithMostEmployees(rows) {
const count = new Map();
for (const [projectId] of rows) {
count.set(projectId, (count.get(projectId) || 0) + 1);
}
const best = Math.max(...count.values());
const out = [];
for (const [p, c] of count) if (c === best) out.push(p);
return out;
}
List<Integer> projectsWithMostEmployees(int[][] rows) {
Map<Integer, Integer> count = new HashMap<>();
for (int[] r : rows) count.merge(r[0], 1, Integer::sum);
int best = Collections.max(count.values());
List<Integer> out = new ArrayList<>();
for (Map.Entry<Integer, Integer> e : count.entrySet())
if (e.getValue() == best) out.add(e.getKey());
return out;
}
vector<int> projectsWithMostEmployees(vector<pair<int,int>>& rows) {
unordered_map<int, int> count;
for (auto& r : rows) count[r.first]++;
int best = 0;
for (auto& kv : count) best = max(best, kv.second);
vector<int> out;
for (auto& kv : count) if (kv.second == best) out.push_back(kv.first);
return out;
}
Explanation
We want the projects with the most employees. The plan is three small steps: count employees per project, find the biggest count, then keep every project that ties for it.
The first pass fills a hash map count where count[project] grows by one for each row of that project. This groups by project and tallies in one sweep.
Next we take best = max(count.values()) — the largest team size — and finally keep every project whose count equals best. We compare to the max (not just pick one) so ties are all returned.
Example: rows = [(1,1),(1,2),(1,3),(2,1),(2,4)]. Counts are project 1 → 3, project 2 → 2. The max is 3, and only project 1 reaches it, so the answer is [1].
If projects 1 and 2 both had 3 employees, both would be returned, since the filter keeps everyone equal to the maximum.