Project Employees I
Problem
You have two tables. Project(project_id, employee_id) maps employees to projects, and Employee(employee_id, name, experience_years) stores each employee's experience. Report, for each project, the average experience years of the employees working on it, rounded to two decimal places. Join the two tables on employee_id, then group by project_id.
Project = [(1,1),(1,2),(2,1)], Employee = [(1,5),(2,7)][(1, 6.00), (2, 5.00)]def project_employees(project, employee):
years = {eid: yrs for eid, yrs in employee}
sums, counts = {}, {}
for pid, eid in project:
sums[pid] = sums.get(pid, 0) + years[eid]
counts[pid] = counts.get(pid, 0) + 1
result = []
for pid in sums:
avg = round(sums[pid] / counts[pid], 2)
result.append((pid, avg))
return result
function projectEmployees(project, employee) {
const years = new Map();
for (const [eid, yrs] of employee) years.set(eid, yrs);
const sums = new Map(), counts = new Map();
for (const [pid, eid] of project) {
sums.set(pid, (sums.get(pid) || 0) + years.get(eid));
counts.set(pid, (counts.get(pid) || 0) + 1);
}
const result = [];
for (const pid of sums.keys()) {
const avg = Math.round((sums.get(pid) / counts.get(pid)) * 100) / 100;
result.push([pid, avg]);
}
return result;
}
List<double[]> projectEmployees(int[][] project, int[][] employee) {
Map<Integer, Integer> years = new HashMap<>();
for (int[] e : employee) years.put(e[0], e[1]);
Map<Integer, Integer> sums = new HashMap<>(), counts = new HashMap<>();
for (int[] p : project) {
sums.merge(p[0], years.get(p[1]), Integer::sum);
counts.merge(p[0], 1, Integer::sum);
}
List<double[]> result = new ArrayList<>();
for (int pid : sums.keySet()) {
double avg = Math.round(100.0 * sums.get(pid) / counts.get(pid)) / 100.0;
result.add(new double[]{ pid, avg });
}
return result;
}
vector<pair<int, double>> projectEmployees(
vector<pair<int,int>>& project, vector<pair<int,int>>& employee) {
unordered_map<int, int> years;
for (auto& e : employee) years[e.first] = e.second;
unordered_map<int, int> sums, counts;
for (auto& p : project) {
sums[p.first] += years[p.second];
counts[p.first] += 1;
}
vector<pair<int, double>> result;
for (auto& kv : sums) {
double avg = round(100.0 * kv.second / counts[kv.first]) / 100.0;
result.push_back({ kv.first, avg });
}
return result;
}
Explanation
We need each project's average experience. An average is just a sum divided by a count, so we build both per project as we scan the assignment rows.
First we make a quick lookup years mapping each employee_id to their experience — this is the "join" done with a hash map, giving instant access to any employee's years.
Then for every (project, employee) row we add that employee's years into sums[pid] and bump counts[pid]. This groups by project in a single pass.
At the end, each project's answer is sums[pid] / counts[pid], rounded to two decimals.
Example: Project 1 has employees 1 (5 yrs) and 2 (7 yrs) → (5+7)/2 = 6.00. Project 2 has only employee 1 → 5/1 = 5.00.