Sort Array by Moving Items to Empty Space - Problem
Imagine you have a sliding puzzle where you need to arrange numbered tiles in order! You're given an integer array nums of size n containing each element from 0 to n-1 (inclusive).
Think of it this way:
- Elements
1ton-1represent numbered tiles - Element
0represents the empty space - In one operation, you can slide any tile into the empty space
Your goal is to sort the array so that:
- All numbered tiles are in ascending order
- The empty space is either at the beginning or end
Valid sorted arrangements:
[0,1,2,3]- empty space at start[1,2,3,0]- empty space at end
Return the minimum number of operations needed to sort the array.
Input & Output
example_1.py โ Basic case with one cycle
$
Input:
nums = [2, 1, 3, 0]
โบ
Output:
2
๐ก Note:
We can sort to [1,2,3,0] with 2 operations: Move 2 to empty space (pos 3): [0,1,3,2], then move 3 to pos 2: [0,1,2,3]. Wait, let me recalculate... Actually, we need to move 0 to position of 2, then 2 to position of 1, creating a cycle that requires 2 swaps total.
example_2.py โ Already sorted case
$
Input:
nums = [0, 1, 2, 3]
โบ
Output:
0
๐ก Note:
The array is already sorted with empty space at the beginning, so no operations are needed.
example_3.py โ Reverse order case
$
Input:
nums = [3, 2, 1, 0]
โบ
Output:
3
๐ก Note:
This creates cycles: 3โ0โ3 (length 2, needs 1 op) and 2โ1โ2 (length 2, needs 1 op), but we need to consider the optimal target configuration which gives us 3 operations total.
Constraints
- 2 โค nums.length โค 105
- 0 โค nums[i] < nums.length
- All the values of nums are unique
- nums contains exactly one occurrence of each integer from 0 to n-1
Visualization
Tap to expand
Understanding the Visualization
1
Identify Valid Targets
There are only two valid sorted arrangements: empty space at start [0,1,2,3] or at end [1,2,3,0]
2
Find Misplaced Tiles
Compare current arrangement with each target to see which tiles are out of place
3
Detect Cycles
Misplaced tiles form cycles - each tile needs to move to where another tile currently is
4
Count Operations
Each cycle of k tiles needs k-1 swap operations to resolve completely
Key Takeaway
๐ฏ Key Insight: The optimal solution recognizes that this is a permutation cycle problem. Elements in their correct position stay put, while misplaced elements form cycles that can be resolved with k-1 swaps for a cycle of length k.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code