Sort Array by Moving Items to Empty Space - Problem

You are given an integer array nums of size n containing each element from 0 to n - 1 (inclusive). Each of the elements from 1 to n - 1 represents an item, and the element 0 represents an empty space.

In one operation, you can move any item to the empty space.

nums is considered to be sorted if the numbers of all the items are in ascending order and the empty space is either at the beginning or at the end of the array.

For example, if n = 4, nums is sorted if:

  • nums = [0,1,2,3] or nums = [1,2,3,0]

...and considered to be unsorted otherwise.

Return the minimum number of operations needed to sort nums.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,3,0]
Output: 2
💡 Note: Target [1,2,3,0]: positions 2 and 3 are correct (3 and 0). So 4-2=2 moves needed.
Example 2 — Already Sorted
$ Input: nums = [0,1,2,3]
Output: 0
💡 Note: Array is already in sorted form [0,1,2,3], so no moves needed.
Example 3 — Alternative Sort
$ Input: nums = [1,2,3,0]
Output: 0
💡 Note: Array is already in alternative sorted form [1,2,3,0], so no moves needed.

Constraints

  • 2 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] < nums.length
  • All the values of nums are unique.

Visualization

Tap to expand
Sort Array by Moving Items to Empty SpaceInput Array:2130[2,1,3,0]Two possible sorted configurations:Target 1:0123Target 2:1230Count correct positions: Target 1 has 1, Target 2 has 2Answer: 4 - max(1,2) = 2 moves needed
Understanding the Visualization
1
Input Array
Array with elements 0 to n-1, where 0 is empty space
2
Two Targets
Check both [0,1,2,3...] and [1,2,3...0] configurations
3
Minimum Moves
Choose target requiring fewer operations
Key Takeaway
🎯 Key Insight: There are exactly two valid sorted states - count elements already correct in each and minimize moves
Asked in
Google 15 Microsoft 12 Amazon 8
23.4K Views
Medium Frequency
~25 min Avg. Time
892 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