oneby7

Range Queries Fenwick tree

609. Create Sorted Array through Instructions

Hard

You are given an array of integers instructions. Start with an empty list nums, and insert the values of instructions into it one at a time, from left to right. nums stays sorted after every insertion.

Each insertion has a cost. Count the values already in nums that are strictly smaller than the new value, and the values already in nums that are strictly larger. The cost is the smaller of the two counts. Values equal to the new value count in neither.

Return the total cost of all the insertions. The total can be large, so return it modulo 109 + 7, which means the remainder after dividing it by 1,000,000,007.

Example 1

Input: instructions = [4, 9, 2, 6, 6, 3, 7]

Output: 4

Explanation: The costs are 0, 0, 0, 1, 1, 1, 1. The second 6 meets [2, 4, 6, 9]: the first 6 is equal, so it counts in neither, and 1 value is smaller and 1 is larger. The 3 meets 1 smaller value and 4 larger ones, so it costs 1.

Example 2

Input: instructions = [7, 7, 7, 7]

Output: 0

Explanation: Every value is equal to the ones already there, so nothing is strictly smaller or larger.

Example 3

Input: instructions = [1000000000, 1, 500000000, 2, 999999999]

Output: 3

Explanation: The first two insertions cost 0. Then 500000000 has 1 smaller and 1 larger value, 2 has 1 smaller and 2 larger, and 999999999 has 3 smaller and 1 larger. Each of the three costs 1.

Check your understanding

Work out the answer for this input before you write any code.

instructions = [3, 1, 4, 1, 5, 9, 2, 6]

Constraints

  • 1 ≤ instructions.length ≤ 105
  • 1 ≤ instructions[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.