Design Boss Hierarchy Tracker

You are given n employees in a company, numbered from 1 to n.

Initially, every employee is independent, which means each employee is the boss of themselves and has no superior.

You need to process two types of operations:

  • "join", a, b: Employee a is currently a boss, and employee b is also currently a boss; After this operation, boss a becomes a subordinate of boss b.
  • "depth", c: Return the number of superiors employee c must go through to reach the topmost boss. If c is already a boss, return 0.

Design a system that supports these operations efficiently.

Example 1:

Input: calls = ["Bosses", "join", "join", "depth", "join", "depth"], params = [[6], [1, 2], [3, 4], [1], [2, 4], [1]]

Output: [1, 2]

Explanation:

Bosses 1 and 2 are merged, so 1 becomes subordinate of 2.

Bosses 3 and 4 are merged, so 3 becomes subordinate of 4.

  • depth(1) returns 1 because 1 -> 2
  • Then 2 becomes subordinate of 4
  • Now 1 -> 2 -> 4, so depth(1) returns 2

Example 2:

Input: calls = ["Bosses", "depth", "join", "join", "depth", "depth"], params = [[5], [5], [5, 3], [3, 2], [5], [2]]

Output: [0, 2, 0]

Explanation:

Initially, every employee is their own boss.

  • depth(5) returns 0
  • 5 becomes subordinate of 3
  • 3 becomes subordinate of 2
  • depth(5) returns 2 because 5 -> 3 -> 2
  • depth(2) returns 0 because 2 is still a boss

Now Your Turn!

Pick the correct output for the given input

Input: calls = ["Bosses", "join", "join", "join", "depth"], params = [[7], [6, 1], [1, 4], [4, 7], [6]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n <= 3 * 105
  • 1 <= number of operations <= 3 * 105
  • For a "join" operation: 1 <= a, b <= n, a != b, both a and b are guaranteed to be bosses at the time of the operation
  • For a "depth" operation: 1 <= c <= n, For every "depth" operation, return the number of superiors between employee c and the current topmost boss

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Bosses {
public:
Bosses(int n) {
}
 
void join(int a, int b) {
}
 
int depth(int c) {
}
};
Test Case

Input:

Calls
Params