Last Updated: 9 Sep, 2025

The Binary Tree Lineage

Easy
Asked in company
PhonePe

Problem statement

In a distant galaxy, a species' lineage is tracked using an infinite binary tree. The gender of each individual is determined by a simple set of genetic rules:

  • The ancestor at the root of the tree (level 1) is a Male ('M').
  • If a parent is a Male ('M'), their left child is a Male ('M') and their right child is a Female ('F').
  • If a parent is a Female ('F'), their left child is a Female ('F') and their right child is a Male ('M').

  • You are given n (a level in the tree, 1-indexed) and k (a position within that level, 1-indexed from left to right). Your task is to determine the gender of the individual at that specific position.


    Input Format:
    A single line containing two space-separated integers, n and k.
    


    Output Format:
    Print a single character, either 'M' or 'F', representing the gender of the individual at the specified location.
    


    Note:
    Level n of the tree contains 2^(n-1) individuals.
    
    Building the tree or the string for a large n is not feasible due to memory and time constraints. The solution must use the recursive structure of the problem to work backwards from the target position to the root.
    
    The first half of any level is an exact copy of the previous level. The second half of any level is an inverted copy of the previous level (M becomes F, F becomes M).