Ctrl K

Cost of Filling a Sorted Shelf

Hard
A librarian fills an initially empty shelf, keeping the books in increasing order of their codes. The books arrive one at a time in the order of the array codes, where codes[i] is the code of the i-th book; codes may repeat. To put a book in its place, the neighbours on one side have to be shifted, and the librarian picks the side with less shifting. So the cost of inserting a book with code x is the smaller of two numbers: how many books already on the shelf have a code strictly less than x, and how many have a code strictly greater than x. Return the total cost of placing all the books, modulo 10⁹ + 7.
Example 1
codes=[4, 8, 2, 6] → 1

4 goes onto the empty shelf: 0. For 8 there is one smaller book and no larger one: 0. For 2 nothing is smaller: 0. For 6 two are smaller (2 and 4) and one is larger (8): 1. The total is 1.

Example 2
codes=[5, 5, 1, 9, 5, 3] → 2

The costs in order are 0, 0, 0, 0, 1 (for the third 5 one book is smaller and one larger), 1 (for 3 one is smaller and four are larger). Equal codes count as neither smaller nor larger. The total is 2.

Example 3
codes=[7] → 0
Constraints
  • 1 ≤ len(codes) ≤ 10⁵
  • 1 ≤ codes[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSmaller Values to the Right HardWindow Sums Within a Band HardPairs With a Steep Drop HardTriples Both Rankings Agree On HardPairs Within a Shifted Gap Hard
loading Python…
Input
codes=[4, 8, 2, 6]
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 116 tests on the server, hidden ones included.