VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-profession-in-a-hypothetical-special-situation/

⇱ Find profession in a special family - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find profession in a special family

Last Updated : 26 May, 2026

Consider a special family of Engineers and Doctors with following rules : 

  1. Everybody has two children.
  2. First child of an Engineer is an Engineer and second child is a Doctor.
  3. First child of an Doctor is Doctor and second child is an Engineer.
  4. All generations of Doctors and Engineers start with Engineer.

We can represent the situation using below diagram: 

πŸ‘ blobid0_1749212726


Given level and position of a person in above ancestor tree, find the profession of the person.
Examples :

Input : level = 4, pos = 2
Output : Doctor

Input : level = 3, pos = 4
Output : Engineer

[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.

Output
Level: 3, Position: 4 -> Engineer
Comment
Article Tags: