Create Sorted Array through Instructions - Problem
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
numsthat are strictly less thaninstructions[i]. - The number of elements currently in
numsthat are strictly greater thaninstructions[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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code