Algorithms

Moves to tidy a bookshelf

Moves to tidy a bookshelf

A tidying robot puts a shelf of books into increasing order of height, working the way a person sorts a hand of cards. It takes the second book, slides it left past every book taller than it, and drops it into the gap. Then the third book, and so on to the end of the shelf.

Sliding one book one place to the right is one move, and the robot's battery is spent on moves. Write shifts_to_tidy(heights), which returns the total number of moves the robot makes while tidying the whole shelf. Lifting a book out and dropping it into the gap is free; only the sliding costs.

Worked example: with heights = [5, 2, 9, 1] the robot first places 2, sliding 5 one place right, which is 1 move. It then places 9, which slides nothing, because 5 is not taller than 9. It then places 1, sliding 9, then 5, then 2, which is 3 more moves. The total is 4.

  • Constraints: the shelf holds between 0 and 2000 books, and each height is between -1000000 and 1000000.
  • Books of equal height are never slid past each other, so a shelf of identical books costs 0 moves.
  • An already tidy shelf costs 0 moves, and a shelf in exactly the wrong order costs the most possible.
  • Simulating the robot is a perfectly good solution here. With 2000 books the worst case is about two million moves, which is well inside any budget.
Code

Run your code to see how it does on the examples. Submit also runs the hidden cases.