Skip to the content

The three closest

Problem

Someone about to join the company has been offered 2700 a month, and before signing asks who they'll be compared with. HR puts together a sheet with the three people whose salary is closest to that offer, whether they earn more or less.

Show the name, the salary, and the distance from 2700, in that order. The distance is never negative: someone who earns 2400 and someone who earns 3000 both get 300.

The shortest distance goes first, and ties go by name. The sheet has room for three.

What it has to return

These rows, in this order

namesalarydistance
Frank2600100
Grace2400300
Lydia3000300

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 name, salary,
  salary - 2700 AS distance
FROM employees
ORDER BY distance;
Solve this challenge

It opens in your browser, with the editor and the tests. It is free and you do not need an account to start.

More O(log n) challenges

See all challenges →