Sponsored
Sponsored
This approach involves grouping employees by their department and filtering their salaries to get the top three unique salaries for each department. By using structures such as dictionaries in our programming languages, we can mimic SQL-like GROUP BY and LIMIT operations. This involves two major steps: Grouping employees by department and then filtering by top salaries.
Time Complexity: O(n log n), dominated by the sorting step where n is the number of employees. Space Complexity: O(n), to store grouped employees and unique salaries.
1const employees = [
2 {id: 1, name: 'Joe', salary: 85000, departmentId: 1},
3 {id: 2, name: 'Henry', salary: 80000, departmentId: 2},
4 {id: 3, name: 'Sam', salary: 60000, departmentId: 2},
5 {id: 4, name: 'Max', salary: 90000, departmentId: 1},
6 {id: 5, name: 'Janet', salary: 69000, departmentId: 1},
7 {id: 6, name: 'Randy', salary: 85000, departmentId: 1},
8 {id: 7, name: 'Will', salary: 70000, departmentId: 1}
9];
10const departments = [
11 {id: 1, name: 'IT'},
12 {id: 2, name: 'Sales'}
13];
14
15const groupByDepartment = (employees) => {
16 const deptMap = new Map();
17 employees.forEach(emp => {
18 if (!deptMap.has(emp.departmentId)) {
19 deptMap.set(emp.departmentId, []);
20 }
21 deptMap.get(emp.departmentId).push(emp);
22 });
23 return deptMap;
24};
25
26const deptEmployees = groupByDepartment(employees);
27
28const result = [];
29
30for (let {id, name} of departments) {
31 const empList = deptEmployees.get(id);
32 const uniqueSalaries = [...new Set(empList.map(emp => emp.salary))];
33 uniqueSalaries.sort((a, b) => b - a);
34 const topSalaries = uniqueSalaries.slice(0, 3);
35
36 empList.forEach(emp => {
37 if (topSalaries.includes(emp.salary)) {
38 result.push({Department: name, Employee: emp.name, Salary: emp.salary});
39 }
40 });
41}
42
43console.log(result);
In JavaScript, we use a Map to group employees by their department. The use of ES6 features like Set helps extract unique salaries. The solution then involves filtering employees by those who have salaries within the top three unique salaries obtained per department.
This approach involves using a more sophisticated data structure to keep track of top salaries and employees proactively while grouping the employees by department. In certain languages, this can be achieved efficiently using priority queues or heaps. However, this example shows a simpler method utilizing sorted structures.
Time Complexity: O(n log n), caused by the sort operation on each department's employee list. Space Complexity: O(n), due to storage needs for set and list of employees per department.
1import java.util.*;
2
3public class TopSalaries
This Java solution groups employees by departments and sorts the list by salary to filter the top three unique salaries. The use of lists and sets helps us manage unique top salaries and efficiently output all qualifying employees.