1789. Primary Department for Each Employee LeetCode Solution
In this guide, you will get 1789. Primary Department for Each Employee LeetCode Solution with the best time and space complexity. The solution to Primary Department for Each Employee problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Primary Department for Each Employee solution in C++
- Primary Department for Each Employee solution in Java
- Primary Department for Each Employee solution in Python
- Additional Resources

Problem Statement of Primary Department for Each Employee
Table: Employee
+—————+———+
| Column Name | Type |
+—————+———+
| employee_id | int |
| department_id | int |
| primary_flag | varchar |
+—————+———+
(employee_id, department_id) is the primary key (combination of columns with unique values) for this table.
employee_id is the id of the employee.
department_id is the id of the department to which the employee belongs.
primary_flag is an ENUM (category) of type (‘Y’, ‘N’). If the flag is ‘Y’, the department is the primary department for the employee. If the flag is ‘N’, the department is not the primary.
Employees can belong to multiple departments. When the employee joins other departments, they need to decide which department is their primary department. Note that when an employee belongs to only one department, their primary column is ‘N’.
Write a solution to report all the employees with their primary department. For employees who belong to one department, report their only department.
Return the result table in any order.
The result format is in the following example.
Example not found
Constraints not found
Complexity Analysis
- Time Complexity: Google AdSense
- Space Complexity: Google Analytics
1789. Primary Department for Each Employee LeetCode Solution in C++
SELECT
employee_id,
department_id
FROM Employee
WHERE primary_flag = 'Y'
UNION DISTINCT
SELECT
employee_id,
department_id
FROM Employee
GROUP BY 1
HAVING COUNT(*) = 1;
/* code provided by PROGIEZ */
1789. Primary Department for Each Employee LeetCode Solution in Java
N/A
// code provided by PROGIEZ
1789. Primary Department for Each Employee LeetCode Solution in Python
N/A
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.