Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Create Sorted Array through Instructions

XPChallenge Points: 30
levelLevel: Hard

You are given an array instructions. We begin with an empty list nums.
We process instructions from left to right, inserting each value into nums while maintaining non-decreasing order.

For each insertion of instructions[i], the cost is calculated as:

  • The count of elements already in nums that are smaller than instructions[i]

  • The count of elements already in nums that are greater than instructions[i]

The insertion cost is the minimum of these two counts.

After inserting all elements, return the total accumulated cost.
Because the cost may be large, return the result modulo 10⁹ + 7.

Example 1:

Input: instructions = [2,1,2]

Output: 1

Explanation:

Insert 2 → cost = 0 → nums = [2] Insert 1 → cost = min(0,1) = 0 → nums = [1,2] Insert 2 → cost = min(1,0) = 0 → nums = [1,2,2] Total cost = 0 + 0 + 0 = 0

Example 2:

Input: instructions = [4,3,2,1]

Output: 3

Explanation:

Insert 4 → 0 Insert 3 → min(0,1)=0 Insert 2 → min(0,2)=0 Insert 1 → min(0,3)=0 Total = 0 (All descending inserts cost 0)

Example 3:

Input: instructions = [2,4,1,3]

Output: 2

Explanation:

Insert 2 → 0 → [2] Insert 4 → 0 → [2,4] Insert 1 → min(0,2)=0 → [1,2,4] Insert 3 → min(2,1)=1 → [1,2,3,4] Total cost = 1

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result