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 (index i is 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
Minimum Unlocked Indices to Sort Nums INPUT nums array: 3 1 2 3 i=0 i=1 i=2 i=3 locked array: 1 1 0 1 = Locked = Unlocked Goal: Sort [3,1,2,3] to [1,2,3,3] Swap rule: nums[i]-nums[i+1]==1 AND locked[i]==0 ALGORITHM STEPS 1 Check swaps needed 3-1=2 (no), 1-2=-1 (no) 2-3=-1 (no direct swap) 2 Find blocking pairs Index 0: 3,1 diff=2 (blocked) Need to move 3 right 3 Greedy unlock Unlock index 1 (locked[1]=0) Now can swap at i=1 4 Simulate sorting [3,1,2,3] unlock i=1 [1,3,2,3] swap possible [1,2,3,3] sorted! Operations needed: unlock(1): locked[1]=0 Total unlocks: 1 FINAL RESULT Before: 3 1 2 3 After sorting: 1 2 3 3 Output: 1 Array sorted with 1 unlock operation Key Insight: Greedy approach: Scan left to right, unlock indices only when necessary to enable required swaps. A swap at index i is needed when nums[i] - nums[i+1] == 1 and current order is wrong. Return -1 if sorting is impossible even with all indices unlocked (structural constraint). TutorialsPoint - Minimum Unlocked Indices to Sort Nums | Greedy Simulation Approach
Asked in
Google 25 Microsoft 20
21.3K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen