FunctionRacerProblemsRace

Shortest Walk to Seats

BeginnerGreedyPython, JavaScript, TypeScript, Java, C++

seats and students list positions on a number line and have the same length. Every student must end up in a different seat, one student per seat, and a student who walks from position p to a seat at position q walks |p - q| units. Positions may repeat in either list.

Return the smallest possible total distance walked by all students. The smallest total is the same for every assignment that achieves it, so no tie rule is needed. Return 0 when both lists are empty.

Example 1

seats [3,1,5]
students [2,7,4]
returns 4

Seats 1, 3, 5 and students 2, 4, 7 in sorted order: the students walk 1, 1 and 2 units.

Example 2

seats [4,1,5,9]
students [1,3,2,6]
returns 7

The student at 1 keeps the seat at 1; the others walk 2, 2 and 3 units.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Greedy problems