You are given an array nums consisting of integers between 1 and 3, and a binary array locked of the same size.
We consider numssortable 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 numssortable. If it is not possible to make nums sortable, return -1.
To make the array sortable, every number must be able to reach its correct position using allowed swaps. If a ‘3’ appears before the last ‘1’, it is impossible to sort the array, as swaps cannot move ‘3’ past ‘1’. We track the first and last positions of each number and check for locked indices in critical ranges. Any locked index in these ranges must be unlocked to allow sorting.
classSolution:
defminUnlockedIndices(self, nums: list[int], locked: list[int]) -> int:
n = len(nums)
first2, first3 = n, n
last1, last2 =-1, -1for i, x in enumerate(nums):
if x ==1:
last1 = i
elif x ==2:
first2 = min(first2, i)
last2 = i
elif x ==3:
first3 = min(first3, i)
if first3 < last1:
return-1 ans =0for i in range(n):
if locked[i] ==1and ((first2 <= i < last1) or (first3 <= i < last2)):
ans +=1return ans
classSolution {
funminUnlockedIndices(nums: IntArray, locked: IntArray): Int {
val n = nums.size
var first2 = n
var first3 = n
var last1 = -1var last2 = -1for (i in0 until n) {
when (nums[i]) {
1-> last1 = i
2-> {
first2 = minOf(first2, i)
last2 = i
}
3-> first3 = minOf(first3, i)
}
}
if (first3 < last1) return -1var ans = 0for (i in0 until n) {
if (locked[i] ==1&& ((first2 <= i && i < last1) || (first3 <= i && i < last2))) {
ans++ }
}
return ans
}
}
impl Solution {
pubfnmin_unlocked_indices(nums: Vec<i32>, locked: Vec<i32>) -> i32 {
let n = nums.len();
letmut first2 = n asi32;
letmut first3 = n asi32;
letmut last1 =-1;
letmut last2 =-1;
for (i, &x) in nums.iter().enumerate() {
if x ==1 {
last1 = i asi32;
} elseif x ==2 {
first2 = first2.min(i asi32);
last2 = i asi32;
} elseif x ==3 {
first3 = first3.min(i asi32);
}
}
if first3 < last1 {
return-1;
}
letmut ans =0;
for i in0..n {
if locked[i] ==1&& ((first2 <= i asi32&& i asi32< last1) || (first3 <= i asi32&& i asi32< last2)) {
ans +=1;
}
}
ans
}
}