Reconcile Employee Project Hours Across Two Tables
SQL & DataAuto-graded · 13 test casesLast updated
Tests the ability to join two lists of dicts (employees and time-log entries) and compute per-employee aggregated project statistics, mimicking a SQL left join + GROUP BY.
Reconcile Employee Project Hours Across Two Tables
You are given two tables represented as lists of dictionaries.
employees — one row per employee:
| field | type | description |
|---|---|---|
employee_id | int | unique identifier |
name | str | full name |
department | str | department name |
logs — one row per work-log entry (an employee may have many entries, or none):
| field | type | description |
|---|---|---|
employee_id | int | references an employee |
project | str | project code (non-empty string) |
hours | float | hours worked (always > 0) |
Your task is to produce a summary report — one record per employee — equivalent to this SQL:
SELECT e.employee_id,
e.name,
e.department,
COUNT(DISTINCT l.project) AS num_projects,
COALESCE(SUM(l.hours), 0.0) AS total_hours,
COALESCE(MAX(l.hours), 0.0) AS max_single_log
FROM employees e
LEFT JOIN logs l ON e.employee_id = l.employee_id
GROUP BY e.employee_id, e.name, e.department
Return a list of dicts, one per employee, each with exactly these keys:
"employee_id"(int)"name"(str)"department"(str)"num_projects"(int) — number of distinct project codes logged by this employee"total_hours"(float) — sum of all hours logged;0.0if no logs"max_single_log"(float) — maximum hours in a single log entry;0.0if no logs
Ordering
Sort the result primarily by department (ascending, case-sensitive lexicographic), secondarily by employee_id (ascending).
Notes
employeescontains no duplicateemployee_idvalues.logsmay reference only a subset of employees; employees with no logs still appear in the output.logsmay contain multiple entries for the same(employee_id, project)pair — all such entries contribute tototal_hoursandmax_single_log; the project is counted only once innum_projects.- An
employee_idthat appears inlogsbut not inemployeesshould be silently ignored. total_hoursandmax_single_logmust be plain Pythonfloatvalues (notint).
Constraints
0 ≤ len(employees) ≤ 20000 ≤ len(logs) ≤ 100001 ≤ employee_id ≤ 10^60.0 < hours ≤ 500.0- Department names and project codes are non-empty strings of printable ASCII characters.
Examples
Example 1
Input: reconcile_hours([{'employee_id': 1, 'name': 'Alice', 'department': 'Engineering'}, {'employee_id': 2, 'name': 'Bob', 'department': 'Marketing'}, {'employee_id': 3, 'name': 'Carol', 'department': 'Engineering'}], [{'employee_id': 1, 'project': 'Alpha', 'hours': 3}, {'employee_id': 1, 'project': 'Beta', 'hours': 5}, {'employee_id': 1, 'project': 'Alpha', 'hours': 2}, {'employee_id': 3, 'project': 'Beta', 'hours': 8}])
Output: [{'employee_id': 1, 'name': 'Alice', 'department': 'Engineering', 'num_projects': 2, 'total_hours': 10, 'max_single_log': 5}, {'employee_id': 3, 'name': 'Carol', 'department': 'Engineering', 'num_projects': 1, 'total_hours': 8, 'max_single_log': 8}, {'employee_id': 2, 'name': 'Bob', 'department': 'Marketing', 'num_projects': 0, 'total_hours': 0, 'max_single_log': 0}]
Example 2
Input: reconcile_hours([{'employee_id': 10, 'name': 'Dan', 'department': 'HR'}], [])
Output: [{'employee_id': 10, 'name': 'Dan', 'department': 'HR', 'num_projects': 0, 'total_hours': 0, 'max_single_log': 0}]
Example 3
Input: reconcile_hours([{'employee_id': 5, 'name': 'Eve', 'department': 'Finance'}, {'employee_id': 6, 'name': 'Frank', 'department': 'Finance'}], [{'employee_id': 5, 'project': 'X', 'hours': 4.5}, {'employee_id': 5, 'project': 'X', 'hours': 1.5}, {'employee_id': 99, 'project': 'Y', 'hours': 7}])
Output: [{'employee_id': 5, 'name': 'Eve', 'department': 'Finance', 'num_projects': 1, 'total_hours': 6, 'max_single_log': 4.5}, {'employee_id': 6, 'name': 'Frank', 'department': 'Finance', 'num_projects': 0, 'total_hours': 0, 'max_single_log': 0}]
Hints
Hint 1
Build a dictionary keyed by employee_id from the logs list before iterating over employees — this gives O(1) lookup and avoids a nested loop.
Hint 2
Use a nested dict or collections.defaultdict to accumulate, per employee, the set of distinct projects plus running sum and running max of hours.
Hint 3
Remember the LEFT JOIN semantics: every employee must appear in the output even if they have zero matching log rows — handle the missing-key case explicitly.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is a classic left join + group-by aggregation, implemented entirely in Python using dictionaries.
Step 1 — Index the logs table
Iterate over logs once and build a dictionary keyed by employee_id. For each key, store:
- a set of distinct project codes (for
num_projects) - a running sum of hours (for
total_hours) - a running maximum of hours (for
max_single_log)
This mirrors what a database engine does when it builds a hash-aggregate on the right-hand side before the join.
Step 2 — Left-join by iterating employees
For each employee in employees, look up their employee_id in the aggregated dictionary. If found, read the pre-computed values; otherwise default everything to 0 / 0.0. This guarantees every employee appears exactly once (LEFT JOIN semantics). Employees referenced only in logs are naturally excluded because we never look at the aggregated dict keys independently.
Step 3 — Sort
Sort the result list by (department, employee_id) to satisfy the ordering requirement.
Correctness
- Distinct project count uses a Python
set, so repeated(employee_id, project)pairs contribute only once tonum_projects. total_hoursandmax_single_logaccumulate all rows, regardless of project repetition.- Orphan log entries (unknown
employee_id) are harmlessly stored inaggbut never joined to any output row.
Complexity
| Time | Space | |
|---|---|---|
| Build log index | O(L) | O(L) |
| Join + output | O(E) | O(E) |
| Sort | O(E log E) | O(1) extra |
| Total | O((E + L) + E log E) | O(E + L) |
where E = len(employees), L = len(logs).
from typing import List, Dict, Any
from collections import defaultdict
def reconcile_hours(employees: list, logs: list) -> list:
# Step 1: aggregate logs by employee_id
agg: Dict[int, Dict] = defaultdict(lambda: {
"projects": set(),
"total_hours": 0.0,
"max_single_log": 0.0,
})
for entry in logs:
eid = entry["employee_id"]
hrs = float(entry["hours"])
agg[eid]["projects"].add(entry["project"])
agg[eid]["total_hours"] += hrs
if hrs > agg[eid]["max_single_log"]:
agg[eid]["max_single_log"] = hrs
# Step 2: left-join — iterate employees, look up aggregated data
result = []
for emp in employees:
eid = emp["employee_id"]
if eid in agg:
data = agg[eid]
num_projects = len(data["projects"])
total_hours = data["total_hours"]
max_single = data["max_single_log"]
else:
num_projects = 0
total_hours = 0.0
max_single = 0.0
result.append({
"employee_id": eid,
"name": emp["name"],
"department": emp["department"],
"num_projects": num_projects,
"total_hours": total_hours,
"max_single_log": max_single,
})
# Step 3: sort by department ASC, then employee_id ASC
result.sort(key=lambda r: (r["department"], r["employee_id"]))
return result