#1649

Create Sorted Array through Instructions

Hard Fenwick tree counting

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Insert numbers one by one into a sorted container. Each insertion costs min(count of existing numbers strictly less, count strictly greater). Return the total cost modulo 1e9+7.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: inserting each number costs min(smaller already in, bigger already in); total cost?

Why this works: a Fenwick tree indexed by value counts how many inserted numbers are below or above x in O(log M).

Example: [1, 5, 6, 2]

1: 0, 5: 0, 6: 0, 2: min(1 smaller, 2 bigger) = 1 → total 1

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Counting "greater" as inserted − prefix(x − 1), which wrongly includes equal values.

Solve on LeetCode ↗
Complexity
  • Time: O(n log M), M = max value.
  • Space: O(M).
Topic: Segment Tree, Fenwick & Sparse Table
🎬 Episodes 98–100: video coming soon