Sort Array by Moving Items to Empty Space — LeetCode 2459 Python Solution
- Problem
- #2459
- Pattern
- Greedy
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums = [4,2,0,3,1]
- Output
- 3
- Explanation
- - Move item 2 to the empty space. Now, nums = [4,0,2,3,1].
Python solution
class Solution:
def sortArray(self, nums: List[int]) -> int:
def f(nums, k):
vis = [False] * n
cnt = 0
for i, v in enumerate(nums):
if i == v or vis[i]:
continue
cnt += 1
j = i
while not vis[j]:
vis[j] = True
cnt += 1
j = nums[j]
return cnt - 2 * (nums[k] != k)
n = len(nums)
a = f(nums, 0)
b = f([(v - 1 + n) % n for v in nums], n - 1)
return min(a, b)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2459. Sort Array by Moving Items to Empty Space is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2459. Sort Array by Moving Items to Empty Space?
- LeetCode 2459. Sort Array by Moving Items to Empty Space is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2459. Sort Array by Moving Items to Empty Space?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2459. Sort Array by Moving Items to Empty Space?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2459. Sort Array by Moving Items to Empty Space cover?
- LeetCode 2459. Sort Array by Moving Items to Empty Space is tagged Greedy, Array and Sorting on LeetCode.
- Is LeetCode 2459. Sort Array by Moving Items to Empty Space a premium problem?
- Yes. LeetCode 2459. Sort Array by Moving Items to Empty Space is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.