Given an integer array instructions, you are asked to create a sorted array from the elements in instructions. You start with an empty container nums.

For each element from left to right in instructions, insert it into nums. The cost of each insertion is the minimum of the following:

  • The number of elements currently in nums that are strictly less than instructions[i].
  • The number of elements currently in nums that are strictly greater than instructions[i].

For example, if inserting element 3 into nums = [1,2,3,5], the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3, element 5 is greater than 3) and nums will become [1,2,3,3,5].

Return the total cost to insert all elements from instructions into nums. Since the answer may be large, return it modulo 10⁹ + 7.

Input & Output

Example 1 — Basic Case
$ Input: instructions = [1,5,6,2]
Output: 1
💡 Note: Insert 1: cost=0. Insert 5: smaller=[1], larger=[], cost=0. Insert 6: smaller=[1,5], larger=[], cost=0. Insert 2: smaller=[1], larger=[5,6], cost=min(1,2)=1. Total=1.
Example 2 — Multiple Costs
$ Input: instructions = [1,2,3,6,5,4]
Output: 3
💡 Note: Each insertion incurs the minimum of smaller/larger elements count. Cost accumulates as: 0+0+0+0+1+2=3.
Example 3 — Duplicates
$ Input: instructions = [1,3,3,3,2,4,2,1,2]
Output: 4
💡 Note: When inserting duplicates, they don't count as strictly smaller or larger, minimizing costs in some cases.

Constraints

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

Visualization

Tap to expand
Create Sorted Array: Insert [1,5,6,2] with Cost TrackingInstructions:1562Step-by-step insertion:Insert 1: [] → [1], cost = min(0,0) = 0Insert 5: [1] → [1,5], smaller=1, larger=0, cost = 0Insert 6: [1,5] → [1,5,6], smaller=2, larger=0, cost = 0Insert 2: [1,5,6] → [1,2,5,6], smaller=1, larger=2, cost = 1Final sorted array:1256Total Cost: 0 + 0 + 0 + 1 = 1Costly insertion
Understanding the Visualization
1
Input
Array of instructions to insert: [1,5,6,2]
2
Process
Insert each element, calculate min(smaller, larger) as cost
3
Output
Return total accumulated insertion cost
Key Takeaway
🎯 Key Insight: The cost is always the minimum of smaller or larger elements, favoring insertions at array ends
Asked in
Google 15 Amazon 12 Microsoft 8
28.0K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen