AnalystPath

Everyone Under the Squadron Commander

PandasMediumMid level~10 min

Problem

You are given a DataFrame `officers` with columns `officer_id`, `officer_name`, and `superior_id`. Each row says the officer reports to the officer whose id is `superior_id`. The squadron commander is `officer_id = 1` (the commander's `superior_id` is their own id).

Find the `officer_id` of every officer who reports to the squadron commander (id = 1) **directly or indirectly**. Indirect means a chain: A reports to B, B reports to C, and C reports to the commander. The chain of command is at most 3 levels deep below the commander.

Do not include the commander themself. Return `officer_id` in any order.

Input data

Example rows — the live problem includes the full dataset.

officers
officer_idofficer_namesuperior_id
1Reyes1
3Tariq3
2Singh1
4Nkomo2
7Petrov4

Expected output

Your answer should return 4 rows with the columns officer_id.

Starter code (Pandas (Python))

import pandas as pd

def under_the_commander(officers) -> pd.DataFrame:
    # Your code here
    return officers

Solve this Pandas question free

Write Pandas (Python) and run it instantly in your browser — even on your phone. No signup needed to try.

Solution & explanation

Create a free account to unlock the optimal solution, a step-by-step explanation, and the hidden test cases that grade your answer.

Sign up free to unlock

Related Pandas questions