"Sort Array by Moving Items to Empty Space" is a complex "Hard" difficulty problem that feels like a sliding puzzle. You are given an array that is a permutation of to , where represents an "empty space." You can move any number into the empty space. Your goal is to find the minimum number of moves to sort the array into one of two targets:
This problem isn't just about sorting; it's about finding the shortest sequence of swaps where one of the swapped elements is always the designated "zero."
Google asks this question to see if candidates can visualize a sorting problem as a graph problem—specifically, identifying cycles. It tests your ability to think beyond standard sorting algorithms and understand the mechanics of permutations. It requires a deep understanding of how "swaps" affect the structure of an array and how to minimize those swaps by leveraging the "empty space" effectively.
The problem can be solved using Cycle Decomposition. In any permutation, the elements form a set of disjoint cycles. To sort an array using swaps, the number of swaps needed is typically . However, because we can only swap with the "empty space" (0), the logic changes slightly.
cycle_size - 1 moves to fix that cycle.cycle_size moves), and we end up with 0 in the correct spot.Input: [1, 0, 2] Target: [0, 1, 2]
The biggest mistake is trying to use BFS to find the shortest path. While BFS works for small arrays, the state space () is too large for typical constraints. Another error is not realizing that there are two possible sorted targets and that you must calculate the minimum moves for both and take the overall minimum. Candidates also often struggle to correctly implement the cycle-finding logic, especially the special handling for when the 0 is already in its target position but other elements are not.
This "Sort Array by Moving Items to Empty Space coding problem" is a great way to learn about Permutation Cycles. Practice similar problems like "Minimum Swaps to Sort." Understand that a cycle of length can be sorted in swaps if you can swap any two elements, but the rules change when you have a restricted swap (like swapping with 0). Mastering cycle decomposition will make many "Hard" array problems much easier to handle.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Arithmetic Subarrays | Medium | Solve | |
| Minimum Swaps to Sort by Digit Sum | Medium | Solve | |
| Minimum Index of a Valid Split | Medium | Solve | |
| Analyze User Website Visit Pattern | Medium | Solve | |
| Count Covered Buildings | Medium | Solve |