Minimum Unlocked Indices to Sort Nums Problem
Description
LeetCode Problem 3431.
You are given an array nums consisting of integers between 1 and 3, and a binary array locked of the same size.
We consider nums sortable if it can be sorted using adjacent swaps, where a swap between two indices i and i + 1 is allowed if nums[i] - nums[i + 1] == 1 and locked[i] == 0.
In one operation, you can unlock any index i by setting locked[i] to 0.
Return the minimum number of operations needed to make nums sortable. If it is not possible to make nums sortable, return -1.
Example 1:
Input: nums = [1,2,1,2,3,2], locked = [1,0,1,1,0,1]
Output: 0
Explanation:
We can sort nums using the following swaps:
- swap indices 1 with 2
- swap indices 4 with 5
So, there is no need to unlock any index.
Example 2:
Input: nums = [1,2,1,1,3,2,2], locked = [1,0,1,1,0,1,0]
Output: 2
Explanation:
If we unlock indices 2 and 5, we can sort nums using the following swaps:
- swap indices 1 with 2
- swap indices 2 with 3
- swap indices 4 with 5
- swap indices 5 with 6
Example 3:
Input: nums = [1,2,1,2,3,2,1], locked = [0,0,0,0,0,0,0]
Output: -1
Explanation:
Even if all indices are unlocked, it can be shown that nums is not sortable.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 3locked.length == nums.length0 <= locked[i] <= 1
Solution
Approach: Case Analysis
The array can only be sorted if no 3 comes before a 1: such a pair can never cross. So if the first 3 is left of the last 1, return -1.
Let first2 and first3 be the first positions of 2 and 3, and last1 and last2 the last positions of 1 and 2. Every index in [first2, last1) or [first3, last2) lies on the way of some element that must cross it, so it has to be unlocked. Count the indices in these ranges whose locked[i] is 1; each of them costs one operation.
Complexity: O(n) time and O(1) space.
class Solution:
def minUnlockedIndices(self, nums: List[int], locked: List[int]) -> int:
n = len(nums)
first2 = first3 = n
last1 = last2 = -1
for i, x in enumerate(nums):
if x == 1:
last1 = i
elif x == 2:
first2 = min(first2, i)
last2 = i
else:
first3 = min(first3, i)
if first3 < last1:
return -1
return sum(
st and (first2 <= i < last1 or first3 <= i < last2)
for i, st in enumerate(locked)
)