Problem Description
Given an integer array instructions, the goal is to insert each element from instructions into an initially empty array nums such that nums remains sorted. For every insertion, the cost is defined as the minimum between:
- The number of elements in nums that are strictly less than the current element.
- The number of elements in nums that are strictly greater than the current element. Return the total cost modulo (10^9 + 7).
Key Insights
- To efficiently count elements less than or greater than a given value as nums grows, use a data structure that supports fast range-sum queries and point updates.
- A Binary Indexed Tree (Fenwick Tree) or Segment Tree is ideal for this purpose.
- The overall approach is to process each instruction one by one, updating the data structure and summing up the insertion cost.
- Keep in mind that the current index in the instructions (i.e., the current number of inserted elements) can help determine the number of elements greater than the current element by subtracting the prefix count from i.
Space and Time Complexity
Time Complexity: O(n log m), where n is the number of instructions and m is the maximum value in instructions.
Space Complexity: O(m), for the binary indexed tree.
Solution
The solution uses a Binary Indexed Tree (Fenwick Tree) to maintain counts of inserted numbers efficiently. For each element in instructions:
- Query the BIT to get the count of numbers strictly less than the current number.
- Calculate the count of numbers strictly greater than the current number by subtracting the count of numbers less-than or equal to the current number from the total numbers processed so far.
- The insertion cost is the minimum of these two counts.
- Update the BIT to include the new number. This approach ensures that both update and query operations run in O(log m) time, making it efficient even for large inputs.