KatInterview

Company Hierarchy Query System with Dynamic Updates

Data Structure DesignModel answer
MediumModel answerData Structure Designtreesgraphspreprocessing

Last updated

Build a data structure to efficiently query employee roles and reporting counts in a company hierarchy, then extend it to handle dynamic additions.

You're building an internal tool to query a company's reporting structure. The hierarchy is provided as a list of [manager, report] pairs where each name is a unique string. The structure may have multiple top-level leaders (a forest rather than a single tree) but contains no cycles.

Design and implement a data structure that supports:

Part 1: lookUp(name) should return three pieces of information:

  • role: the string "mgr" if this person manages at least one direct report, otherwise "ic" (individual contributor)
  • directReportCount: how many people report directly to this person
  • totalReportCount: the total size of their organization (all people in their reporting chain, not including themselves)

Part 2: Analyze the time and space complexity of your implementation.

Part 3: If your system will handle many more lookups than updates, how would you optimize it?

Part 4: If lookUp must run in O(1) time, what preprocessing would you perform and what would that cost?

Part 5: Extend your design to support add(managerName, reportName) which creates a new reporting relationship. If either person doesn't exist yet, add them to the system. After calling add, subsequent lookUp calls should reflect the updated structure. Discuss how this impacts your complexity analysis.

Your implementation should handle:

  • Multiple disconnected reporting chains
  • Validation to prevent cycles and duplicate manager assignments
  • Efficient updates to aggregated counts

Include test cases demonstrating correctness.

Hints

Hint 1

Think about whether you want to compute subtree sizes on-demand or precompute them once

Hint 2

For O(1) lookups, you'll need to cache derived information—what exactly needs to be cached?

Hint 3

When adding a new edge, which nodes' counts are affected? Only the ancestors of the manager, not the entire tree