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 through Instructions INPUT instructions array: 1 5 6 2 i=0 i=1 i=2 i=3 Coordinate Compression: Sort: [1,2,5,6] Ranks: 1-->1, 2-->2, 5-->3, 6-->4 Binary Indexed Tree: BIT[1..4] for counting 0 0 0 0 [1] [2] [3] [4] Tracks element frequencies ALGORITHM STEPS 1 Insert 1 (rank=1) smaller=0, larger=0 cost = min(0,0) = 0 2 Insert 5 (rank=3) smaller=1, larger=0 cost = min(1,0) = 0 3 Insert 6 (rank=4) smaller=2, larger=0 cost = min(2,0) = 0 4 Insert 2 (rank=2) smaller=1, larger=2 cost = min(1,2) = 1 BIT Operations: Query(rank-1): count smaller total - Query(rank): count larger Update(rank): add to BIT Time: O(n log n) FINAL RESULT Sorted Array Build: After step 1: 1 After step 2: 1 5 After step 3: 1 5 6 After step 4: 1 2 5 6 Total Cost: 0 + 0 + 0 + 1 = 1 Output: 1 Key Insight: Binary Indexed Tree (BIT) efficiently counts elements in range in O(log n) time. Coordinate compression maps values to ranks [1..n] for compact BIT indexing. For each insertion, query BIT for smaller (rank-1) and larger (total - rank) counts, take minimum as cost. TutorialsPoint - Create Sorted Array through Instructions | Coordinate Compression + Binary Indexed Tree
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