Primary Department for Each Employee — LeetCode 1789 Python Solution
EasyDatabase
- Problem
- #1789
- Reading time
- 3 min
- Source
- leetcode.com
Table schema
SQL
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.Example
SQL
+---------------+---------+
| 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.Python solution
Python
import duckdb
import pandas as pd
def solution(employee: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Employee", employee)
return con.execute("""SELECT employee_id, department_id
FROM Employee
WHERE primary_flag = 'Y'
UNION
SELECT employee_id, department_id
FROM Employee
GROUP BY 1
HAVING COUNT(1) = 1;""").df()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 1789. Primary Department for Each Employee?
- LeetCode 1789. Primary Department for Each Employee is rated Easy on LeetCode.
- What topics does LeetCode 1789. Primary Department for Each Employee cover?
- LeetCode 1789. Primary Department for Each Employee is tagged Database on LeetCode.