Create Sorted Array through Instructions - Problem
You're building a sorted array incrementally by following a sequence of instructions. Starting with an empty container, you'll insert elements one by one, but each insertion comes with a cost!
Given an array instructions, for each element you insert, you must pay the minimum cost between:
- The number of existing elements strictly less than the new element
- The number of existing elements strictly greater than the new element
Example: If you're inserting 3 into [1, 2, 3, 5]:
- Elements less than 3:
[1, 2]โ count = 2 - Elements greater than 3:
[5]โ count = 1 - Cost =
min(2, 1) = 1 - Result:
[1, 2, 3, 3, 5]
Return the total cost to insert all elements. Since the answer can be large, return it modulo 109 + 7.
Input & Output
example_1.py โ Python
$
Input:
instructions = [1,5,6,2]
โบ
Output:
1
๐ก Note:
Insert 1: [], cost = min(0,0) = 0. Insert 5: [1], cost = min(1,0) = 0. Insert 6: [1,5], cost = min(2,0) = 0. Insert 2: [1,5,6], cost = min(1,2) = 1. Total = 1
example_2.py โ Python
$
Input:
instructions = [1,2,3,6,5,4]
โบ
Output:
3
๐ก Note:
Insert sequence: [] โ [1] โ [1,2] โ [1,2,3] โ [1,2,3,6] โ [1,2,3,5,6] โ [1,2,3,4,5,6]. Costs: 0,0,0,0,1,2. Total = 3
example_3.py โ Python
$
Input:
instructions = [1,3,3,3,2,4,2,1,2]
โบ
Output:
4
๐ก Note:
Multiple duplicates create various insertion costs as the array grows and elements can be inserted at different relative positions
Constraints
- 1 โค instructions.length โค 105
- 1 โค instructions[i] โค 105
- Return answer modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Map Book Types
Create index mapping for different page counts (coordinate compression)
2
Range Counter
Use Binary Indexed Tree to efficiently count books in page ranges
3
Smart Insertion
For each new book, quickly count books with fewer/more pages
4
Minimal Shifting
Choose the minimum between shifting lighter or heavier books
Key Takeaway
๐ฏ Key Insight: We don't need the actual sorted array - just efficient range counting! Binary Indexed Tree provides O(log n) updates and queries, making the overall solution O(n log n).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code