Range Queries Fenwick tree
609. Create Sorted Array through Instructions
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]
4Explanation: 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]
0Explanation: 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]
3Explanation: 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.
Constraints
1 ≤ instructions.length ≤ 1051 ≤ instructions[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.