Ctrl K

Locks Between Neighbours

Medium
You are given an array values containing only the numbers 1, 2 and 3, and an array locks of the same length made of zeros and ones. The neighbours at positions i and i + 1 may trade places only when the left one is exactly one greater than the right one (values[i] - values[i + 1] == 1) and lock i is open (locks[i] == 0). Such swaps can be made any number of times. In one operation you can open any lock, setting locks[i] to 0. Return the fewest operations after which values can be sorted in non-decreasing order, or -1 if that is impossible even with every lock open.
Example 1
values=[2, 1, 3, 2], locks=[1, 0, 1, 1] → 2

The 2 and 1 at positions 0–1 must swap, so lock 0 has to be opened. The 3 and 2 at positions 2–3 must swap as well, so lock 2 is opened too. That makes 2.

Example 2
values=[1, 3, 2, 1], locks=[0, 0, 0, 0] → -1

A 3 stands left of the last 1, and a 3 can never swap with a 1 directly, so sorting is impossible.

Example 3
values=[1, 1, 2, 3], locks=[1, 1, 1, 1] → 0

The row is already sorted, nothing needs opening.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • values[i] ∈ {1, 2, 3}
  • len(locks) = len(values)
  • locks[i] ∈ {0, 1}
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSudoku Board Without Clashes MediumAnagram Buckets MediumZero Out the Crosses MediumTree From Pre-Order and In-Order Walks MediumTree From In-Order and Post-Order Walks Medium
loading Python…
Input
values=[2, 1, 3, 2], locks=[1, 0, 1, 1]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 139 tests on the server, hidden ones included.