981. Minimum Unlocked Indices to Sort Nums

Given an integer array nums, where each element is 1, 2, or 3, and a binary array locked of the same length.

We say that nums is sortable if we can sort it in non-decreasing order using adjacent swaps, where a swap between indices i and i + 1 is allowed if:

  • nums[i] - nums[i + 1] == 1
  • locked[i] == 0 (i.e., the element at index i is not locked)

In one operation, you may unlock any index by setting locked[i] = 0. Return the minimum number of unlock operations needed to make nums sortable. If sorting is impossible, return -1.

Example 1:

Input: nums = [2,1,3,2,3,3], locked = [0,1,0,1,0,1]  

Output: 0

Explanation: We can sort nums using the following swaps:

Swap indices 0 and 1

Swap indices 2 and 3

Thus, no unlocking is required.

Example 2:

Input: nums = [2,1,3,2,3,2] , locked = [1,0,1,1,0,1]  

Output:1

Explanation: By unlocking index 5, we can sort nums using the following swaps:

Swap indices 0 and 1

Swap indices 4 and 5

Now Your Turn!

Pick the correct output for the given input

Input: nums = [1,3,3,2,2,1,3], locked = [0,0,0,0,0,0,0]  

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 3
  • locked.length == nums.length
  • 0 ≤ locked[i] ≤ 1

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int minUnlockedIndices(vector<int>& nums, vector<int>& locked) {
}
};
Test Case

Input:

Locked
Nums