Project Employees II

easy hash map group by count

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.

Inputrows = [(1,1), (1,2), (1,3), (2,1), (2,4)]
Output[1]
Project 1 has 3 employees and project 2 has 2, so the maximum is 3 and only project 1 reaches it.

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