Skip to the content

The chain of command

Problem

Someone new joins HR and asks for the org chart. Nobody has ever drawn one: all there is to go on is employees, where each person's row says who their boss is and nothing more.

For each person, show their name, their level, and their chain of command, in that order. The level is how many bosses they have above them: someone with none, like Carol, is at 0. The chain goes in a single cell, from the very top down to the person, with > between one name and the next: Samuel's is Carol > Paige > Samuel, and Carol's is Carol.

Sort by the chain, as the text it is: everyone lands right under their boss, and the org chart draws itself.

What it has to return

These rows, in this order

namelevelchain
Carol0Carol
Grace1Carol > Grace
Mark1Carol > Mark
Nicole2Carol > Mark > Nicole
Rachel2Carol > Mark > Rachel
Paige1Carol > Paige
Frank2Carol > Paige > Frank
Lydia2Carol > Paige > Lydia
Samuel2Carol > Paige > Samuel

This is what comes out with the data in the practice database this challenge uses. The column names don’t count, so name yours however you like: what counts is how many there are and the order they come in. Besides this one, the challenge has hidden tests with other data that are revealed when you submit your solution.

You start with this

SQL

SELECT e.name, b.name AS boss
FROM employees e
LEFT JOIN employees b
  ON e.boss_id = b.id
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(2ⁿ) challenges

See all challenges →