Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1875. Group Employees of the Same Salary - Leetcode Solution

Problem Description

You are given a list of employees, where each employee is represented as an object or structure with at least two properties: name and salary. The task is to group all employees who share the same salary together. The output should be a mapping (such as a dictionary or hash map) where each key is a distinct salary, and the value is a list of names (or employee objects) who earn that salary.

Key constraints:

  • Each employee appears only once in the input list.
  • Do not reuse or duplicate employee entries in the output.
  • The order of employees within each salary group does not matter unless specified.
  • There is only one valid grouping for a given input.

Thought Process

To solve this problem, we need to organize employees by their salary. The naive approach would be to scan the list for each unique salary and collect matching employees, but this would be inefficient, especially for large lists.

Instead, we can leverage a hash map (dictionary) to efficiently group employees as we iterate through the list. For each employee, we check if their salary is already a key in our map; if not, we create a new group. Otherwise, we append the employee to the existing group. This approach ensures we only pass through the list once, making it much more efficient than checking every possible salary for every employee.

This is a classic "group by" problem, and using a hash map allows for quick lookups and insertions as we build our groups.

Solution Approach

Let's break down the steps to solve the problem:

  1. Initialize a hash map: Create an empty dictionary (or map) where each key will be a salary, and each value will be a list of employees (or names) who earn that salary.
  2. Iterate through the employee list: For each employee, check their salary.
  3. Group employees: If the salary is not already in the map, add it with an empty list. Then, append the employee (or their name) to the corresponding list.
  4. Return the result: After processing all employees, return the hash map containing salary groups.

We use a hash map because it allows us to group employees in a single pass, and lookups/insertions are O(1) on average.

Example Walkthrough

Suppose we are given the following list of employees:

  • Alice, salary 5000
  • Bob, salary 6000
  • Charlie, salary 5000
  • Diana, salary 7000
  • Edward, salary 6000
Step-by-step grouping:
  1. Start with an empty map: {}
  2. Process Alice (5000): Add 5000 as a key, value is [Alice]: {5000: ['Alice']}
  3. Process Bob (6000): Add 6000 as a key, value is [Bob]: {5000: ['Alice'], 6000: ['Bob']}
  4. Process Charlie (5000): 5000 exists, append Charlie: {5000: ['Alice', 'Charlie'], 6000: ['Bob']}
  5. Process Diana (7000): Add 7000 as a key, value is [Diana]: {5000: ['Alice', 'Charlie'], 6000: ['Bob'], 7000: ['Diana']}
  6. Process Edward (6000): 6000 exists, append Edward: {5000: ['Alice', 'Charlie'], 6000: ['Bob', 'Edward'], 7000: ['Diana']}

The final output is a mapping from each salary to a list of employee names who earn that salary.

Code Implementation

def group_employees_by_salary(employees):
    salary_groups = {}
    for emp in employees:
        salary = emp['salary']
        name = emp['name']
        if salary not in salary_groups:
            salary_groups[salary] = []
        salary_groups[salary].append(name)
    return salary_groups

# Example usage:
# employees = [{'name': 'Alice', 'salary': 5000}, {'name': 'Bob', 'salary': 6000}, ...]
# print(group_employees_by_salary(employees))
      
#include <unordered_map>
#include <vector>
#include <string>
using namespace std;

struct Employee {
    string name;
    int salary;
};

unordered_map<int, vector<string>> groupEmployeesBySalary(const vector<Employee>& employees) {
    unordered_map<int, vector<string>> salaryGroups;
    for (const auto& emp : employees) {
        salaryGroups[emp.salary].push_back(emp.name);
    }
    return salaryGroups;
}

// Example usage:
// vector<Employee> employees = {{ "Alice", 5000 }, { "Bob", 6000 }, ...};
// auto result = groupEmployeesBySalary(employees);
      
import java.util.*;

class Employee {
    String name;
    int salary;
    Employee(String name, int salary) {
        this.name = name;
        this.salary = salary;
    }
}

public class Solution {
    public Map<Integer, List<String>> groupEmployeesBySalary(List<Employee> employees) {
        Map<Integer, List<String>> salaryGroups = new HashMap<>();
        for (Employee emp : employees) {
            salaryGroups.computeIfAbsent(emp.salary, k -> new ArrayList<>()).add(emp.name);
        }
        return salaryGroups;
    }
}

// Example usage:
// List<Employee> employees = Arrays.asList(new Employee("Alice", 5000), new Employee("Bob", 6000), ...);
// new Solution().groupEmployeesBySalary(employees);
      
function groupEmployeesBySalary(employees) {
    const salaryGroups = {};
    for (const emp of employees) {
        const salary = emp.salary;
        const name = emp.name;
        if (!salaryGroups[salary]) {
            salaryGroups[salary] = [];
        }
        salaryGroups[salary].push(name);
    }
    return salaryGroups;
}

// Example usage:
// const employees = [{name: 'Alice', salary: 5000}, {name: 'Bob', salary: 6000}, ...];
// console.log(groupEmployeesBySalary(employees));
      

Time and Space Complexity

Brute-force approach: For each unique salary, scan the entire employee list to collect matches. If there are n employees and k unique salaries, this is O(n * k) time and O(n) space.

Optimized approach (hash map): We process each employee once, performing O(1) insertion per employee. Thus, time complexity is O(n), where n is the number of employees. The space complexity is also O(n), since in the worst case, each employee has a unique salary.

The hash map makes this grouping efficient and scalable for large datasets.

Summary

The problem of grouping employees by salary is elegantly solved using a hash map to collect employees in a single pass. This approach is efficient, concise, and leverages the natural mapping between keys (salaries) and lists of employees. By focusing on direct grouping rather than repeated scanning, we achieve optimal time and space complexity, making this strategy both practical and elegant for real-world data grouping tasks.