Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2023-09-28
Problem Statement
Design a database system to store and query employee hierarchy within an organization. The system should efficiently support hierarchical queries such as reporting lines, team structures, and managerial relationships.
Department departmentId (PK), name, headEmployeeId (FK to Employee)
Role (Optional) roleId (PK), roleName, permissions
Design Approaches
Adjacency List (Simplest)
•Each employee record stores managerId pointing to their manager.
•Pros: Simple to implement.
•Cons: Recursive queries needed for full hierarchy (may require multiple joins).
Nested Set Model
•Store left and right values to represent hierarchy.
•Pros: Efficient for retrieving subtrees.
•Cons: Expensive updates when hierarchy changes.
Materialized Path
•Store full path as a string (e.g., /CEO/CTO/Manager/Employee).
•Pros: Easy to query subordinates using string matching.
•Cons: Path updates needed when hierarchy changes.
Graph / Recursive Queries (Modern DBs)
•Use graph databases (Neo4j) or relational DBs with recursive CTEs.
•Pros: Flexible, easy to query complex relationships.
•Cons: May require specialized DB knowledge.
Key Queries
Direct Subordinates
12SELECT * FROM EmployeeWHERE managerId =:managerId;
1.All Subordinates (Recursive)
12WITH RECURSIVE subordinates AS (3SELECT employeeId, name FROM EmployeeWHERE managerId =:managerId
4 UNION ALL
5 SELECT e.employeeId, e.name
6 FROM Employee e
7 INNER JOIN subordinates s ON e.managerId = s.employeeId
8)9SELECT *FROM subordinates;
1.Reporting Chain for Employee
12WITH RECURSIVE managers AS (3SELECT employeeId, managerId FROM EmployeeWHERE employeeId =:employeeId
4 UNION ALL
5 SELECT e.employeeId, e.managerId FROM Employee e
6 INNER JOIN managers m ON e.employeeId = m.managerId
7)8SELECT *FROM managers;
1.Find Common Manager Between Two Employees
•Retrieve reporting chains for both employees and find intersection.
Design Considerations
1.Hierarchical Queries
•Optimize for frequent reporting queries using indexes or materialized views.
2.Updates & Promotions
•Ensure changes in managerId propagate correctly.
3.Extensibility
•Add support for multiple reporting managers or dotted-line reporting if required.
4.Performance
•Index on managerId for quick subordinate lookups.
•Consider caching for frequently accessed hierarchies.
✅ This HLD problem tests:
•Ability to model hierarchical data in relational or graph databases.
•Understanding of recursive queries and tree traversal techniques.
•Trade-offs between query performance and update complexity.