[Naive Approach] Using Recursion β O(level) Time and O(level) Space
The idea is to recursively determine the profession of the parent node and then derive the current nodeβs profession based on its position. An engineer produces an engineer at odd position and a doctor at even position, while a doctor produces a doctor at odd position and an engineer at even position. By recursively moving upward to the root, we can determine the profession at the required level and position.
Start from the given (level, position) and recursively move to its parent node
Base case: profession at level 1 is always Engineer
Determine current profession based on parent profession and whether position is odd or even
Return the final profession for the given node
Output
Doctor
[Optimal Approach] Using Bit Manipulation β O(log pos) Time and O(1) Space
The result depends upon on set bit count in (pos - 1). If the count of set bits is even, the profession is Engineer, otherwise, Doctor. Level input isn't necessary because first elements are same, please see the below sequences
Level 1: E Level 2: ED Level 3: EDDE Level 4: EDDEDEED Level 5: EDDEDEEDDEEDEDDE
Every level is obtained by concatenating the previous level and complement of the previous level.
Steps to Solve
Compute (pos - 1) for the given position and number of set bits in it.
If the set bit count is even, return Engineer else Doctor
How does this work?
Let us encode Engineer as 0 and Doctor as 1.
First child keeps the same value and second child flips (complements) the it.
Let us write (pos - 1) in binary. Each bit tells the path from the root: 0 -> first child (no flip) and 1 -> second child (flip)
Therefore, even number of flips -> still Engineer (0) and odd number of flips -> Doctor (1)
That is why the answer depends on the parity of set bits.