Minimum Reverse Operations - Problem

You are given an integer n and an integer p representing an array arr of length n where all elements are set to 0's, except position p which is set to 1.

You are also given an integer array banned containing restricted positions and an integer k representing the size of subarrays you can reverse.

Operation: Reverse a subarray of size k if the single 1 is not at a position in banned.

Return an integer array answer with n results where the ith result is the minimum number of operations needed to bring the single 1 to position i in arr, or -1 if it is impossible.

Input & Output

Example 1 — Basic Case
$ Input: n = 4, p = 0, banned = [1,2], k = 4
Output: [0,-1,-1,1]
💡 Note: Start at position 0. Position 1 and 2 are banned (-1). To reach position 3: reverse entire array [0,1,2,3] with k=4, moving element from position 0 to position 3 in 1 step.
Example 2 — No Banned Positions
$ Input: n = 3, p = 0, banned = [], k = 3
Output: [0,2,1]
💡 Note: Start at 0. Reverse [0,1,2] moves 0→2 (1 step). From 2, reverse [0,1,2] moves 2→0, then reverse moves 0→2→1 (2 steps total to reach 1).
Example 3 — Impossible Case
$ Input: n = 2, p = 0, banned = [], k = 2
Output: [0,1]
💡 Note: Start at 0. Reverse [0,1] with k=2 swaps positions, so 0→1 in 1 step. Both positions reachable.

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ p < n
  • 0 ≤ banned.length ≤ n - 1
  • 0 ≤ banned[i] < n
  • banned[i] ≠ p
  • 2 ≤ k ≤ n

Visualization

Tap to expand
Minimum Reverse Operations - BFS Approach INPUT Initial Array (n=4, p=0): 1 i=0 0 i=1 BAN 0 i=2 BAN 0 i=3 Parameters: n = 4 p = 0 (start pos) banned = [1, 2] k = 4 (subarray size) Position with 1 Banned k=4: reverse entire array [1,0,0,0] --> [0,0,0,1] 1 moves from idx 0 to idx 3 ALGORITHM STEPS 1 Initialize BFS Queue = [0], dist[0] = 0 dist[1,2,3] = -1 2 Process pos=0 Find reachable positions with k=4 reverse 3 Check Reachability From 0: can reach 3 (skip banned 1, 2) 4 Update Distances dist[3] = dist[0] + 1 = 1 Banned positions: -1 BFS Tree: 0 d=0 3 d=1 1 2 FINAL RESULT Minimum Operations Array: 0 start -1 banned -1 banned 1 1 op Output: [0, -1, -1, 1] Explanation: Position 0: 0 ops (start) Position 1: -1 (banned) Position 2: -1 (banned) Position 3: 1 op Reverse [0,1,2,3] moves 1 from 0 to 3 Key Insight: BFS explores positions level-by-level, guaranteeing minimum operations. When reversing a subarray of size k, the position of 1 changes based on reflection formula. Banned positions create "holes" that cannot be visited, making them unreachable (-1). Use ordered sets to efficiently track unvisited positions and skip banned ones. TutorialsPoint - Minimum Reverse Operations | BFS Approach
Asked in
Google 23 Amazon 18 Microsoft 15 Meta 12
21.5K Views
Medium Frequency
~35 min Avg. Time
892 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