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
Binary Indexed Tree: Smart Range CountingSmart Bookshelf with Range Counters50p100p200p500pBinary Indexed Tree StructureTotal: 4โ‰ค200: 3โ‰ค500: 4โ‰ค100โ‰ค200โ‰ค400โ‰ค500Inserting 150-page book150pBooks with < 150 pages:Query= 2 booksBooks with > 150 pages:Query= 2 booksCost = min(2, 2) = 2Time: O(log n) per insertion!
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).
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
89.4K Views
Medium-High Frequency
~35 min Avg. Time
1.8K 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