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 Space INPUT nums = [2, 1, 3, 0] 2 idx 0 1 idx 1 3 idx 2 0 idx 3 Empty Space (0) Items (1 to n-1) Target States: [0,1,2,3] or [1,2,3,0] n = 4 elements Find min ops to sort ALGORITHM STEPS 1 Detect Cycles Find permutation cycles 2 Cycle for [0,1,2,3] 0 at start: count ops 3 Cycle for [1,2,3,0] 0 at end: count ops 4 Return Minimum min(ops1, ops2) Cycle: 0 --> 3 --> 0 0 3 Swap 0 with target pos FINAL RESULT Operation 1: 2 1 0 3 Move 3 to empty space Operation 2: 0 1 2 3 Move 2 to empty, then 1 Sorted: [0,1,2,3] OUTPUT 2 OK - Minimum operations Key Insight: The problem reduces to counting cycle lengths in permutation. When 0 is part of a cycle, we need (cycle_length - 1) ops. When 0 is not in cycle, we need (cycle_length + 1) ops. Compare both target states [0,1,2,3] and [1,2,3,0] and return the minimum total operations. TutorialsPoint - Sort Array by Moving Items to Empty Space | Greedy Cycle Detection
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