Minimum Unlocked Indices to Sort Nums - Problem
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(the left element is exactly 1 greater than the right)locked[i] == 0(indexiis unlocked)
In one operation, you can unlock any index i by setting locked[i] = 0.
Return the minimum number of operations needed to make nums sortable. If it is not possible to make nums sortable, return -1.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [3,1,2,3], locked = [1,1,0,1]
›
Output:
1
💡 Note:
We need to swap 3 and 1 (since 3-1=2≠1, this is invalid). Actually, we can swap positions where difference is exactly 1. We need to unlock position 0 to swap 3→1, then 1→2. Total unlocks: 1.
Example 2 — Already Sorted
$
Input:
nums = [1,2,3], locked = [1,1,1]
›
Output:
0
💡 Note:
Array is already sorted, no swaps needed, so no unlocks required.
Example 3 — Impossible Case
$
Input:
nums = [3,1,1], locked = [0,0,0]
›
Output:
-1
💡 Note:
We need to swap 3 and 1, but 3-1=2≠1, so the swap is not allowed even if unlocked. Cannot sort this array.
Constraints
- 2 ≤ nums.length ≤ 20
- 1 ≤ nums[i] ≤ 3
- locked.length == nums.length
- locked[i] is either 0 or 1
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code