Minimum Unlocked Indices to Sort Nums - Problem
Imagine you have a special array of security codes (integers 1, 2, or 3) that needs to be sorted using adjacent swaps. However, some positions are locked and cannot participate in swaps!
You're given:
nums: An array of integers between 1 and 3locked: A binary array wherelocked[i] = 1means position i is locked
Swapping Rules:
- You can swap
nums[i]andnums[i+1]only if: - โข
nums[i] - nums[i+1] == 1(decreasing by exactly 1) - โข
locked[i] == 0(position i is unlocked)
Goal: Find the minimum number of positions you need to unlock to make the array sortable. Return -1 if impossible.
Example: nums = [3,1,2], locked = [1,0,1]
We need to unlock position 0 to enable swaps, so answer is 1.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [3,1,2], locked = [1,0,1]
โบ
Output:
1
๐ก Note:
We need to unlock position 2 to enable the swap between positions 1 and 2 (since 2-1=1). After unlocking position 2, we can perform swaps to sort the array: [3,1,2] โ [3,2,1] โ [2,3,1] โ [2,1,3] โ [1,2,3].
example_2.py โ Already Sorted
$
Input:
nums = [1,2,3], locked = [1,1,1]
โบ
Output:
0
๐ก Note:
The array is already sorted, so no unlocks are needed. Even though all positions are locked, no swaps are required.
example_3.py โ Impossible Case
$
Input:
nums = [3,2,1], locked = [1,1,1]
โบ
Output:
-1
๐ก Note:
All positions are locked and the array is reverse sorted. Since we can only swap adjacent elements with difference exactly 1, and no swaps are possible with all positions locked, it's impossible to sort this array.
Constraints
- 1 โค nums.length โค 20
- 1 โค nums[i] โค 3
- locked.length == nums.length
- locked[i] is either 0 or 1
- Only adjacent swaps allowed when nums[i] - nums[i+1] = 1 and locked[i] = 0
Visualization
Tap to expand
Understanding the Visualization
1
Initial State
Cards [3,1,2] with positions [๐,๐,๐]. Only position 1 can initiate swaps.
2
Analysis
Need 3โ1โ2 to become 1โ2โ3. Check which swaps are possible with current locks.
3
Strategic Unlock
Unlock position 2 to enable swap between 1 and 2 (since 2-1=1).
4
Sorting Process
Perform allowed swaps: [3,1,2]โ[3,2,1]โ[2,3,1]โ[2,1,3]โ[1,2,3]
Key Takeaway
๐ฏ Key Insight: This problem combines graph theory with optimization. Elements can only bubble sort within connected components, so we need to strategically unlock positions to bridge components that must exchange elements for proper sorting.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code