Skip to main content
Back to problems
#2988
Medium Database

Manager of the largest department

Database
80.9% acceptance
Mar 31, 2026
8
1

No description available.

Solution

Pandas
Time O(n)
Space O(1)
LeetCode
solution.pandas
# Table: Employees
# 
# +-------------+---------+
# | Column Name | Type    |
# +-------------+---------+
# | emp_id      | int     |
# | emp_name    | varchar |
# | dep_id      | int     |
# | position    | varchar |
# +-------------+---------+
# emp_id is column of unique values for this table.
# This table contains emp_id, emp_name, dep_id, and position.
# 
# Write a solution to find the name of the manager from the largest department. There may be multiple largest departments when the number of employees in those departments is the same.
# 
# Return the result table sorted by dep_id in ascending order.
# 
# The result format is in the following example.
#
# Example 1:
# Input:
# Employees table:
# +--------+----------+--------+---------------+
# | emp_id | emp_name | dep_id | position      |
# +--------+----------+--------+---------------+
# | 156    | Michael  | 107    | Manager       |
# | 112    | Lucas    | 107    | Consultant    |
# | 8      | Isabella | 101    | Manager       |
# | 160    | Joseph   | 100    | Manager       |
# | 80     | Aiden    | 100    | Engineer      |
# | 190    | Skylar   | 100    | Freelancer    |
# | 196    | Stella   | 101    | Coordinator   |
# | 167    | Audrey   | 100    | Consultant    |
# | 97     | Nathan   | 101    | Supervisor    |
# | 128    | Ian      | 101    | Administrator |
# | 81     | Ethan    | 107    | Administrator |
# +--------+----------+--------+---------------+
# Output
# +--------------+--------+
# | manager_name | dep_id |
# +--------------+--------+
# | Joseph       | 100    |
# | Isabella     | 101    |
# +--------------+--------+
# Explanation
# - Departments with IDs 100 and 101 each has a total of 4 employees, while department 107 has 3 employees. Since both departments 100 and 101 have an equal number of employees, their respective managers will be included.
# Output table is ordered by dep_id in ascending order.

import pandas as pd

def find_manager(employees: pd.DataFrame) -> pd.DataFrame:
  dept_size = employees.groupby('dep_id').size().reset_index(name='cnt')
  max_size = dept_size['cnt'].max()
  largest_depts = dept_size[dept_size['cnt'] == max_size]['dep_id']
  managers = employees[(employees['dep_id'].isin(largest_depts)) & (employees['position'] == 'Manager')]
  result = managers[['emp_name', 'dep_id']].rename(columns={'emp_name': 'manager_name'})
  return result.sort_values('dep_id')