Approach
Breadth-first search
For Minimum Reverse Operations, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 36 lines of Java from the credited upstream file 2612.java.
- The implementation visibly relies on sequence storage, ordered lookup, work queue.
- 3 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int[] minReverseOperations(int n, int p, int[] banned, int k) {3 Set<Integer> bannedSet = Arrays.stream(banned).boxed().collect(Collectors.toSet());4 int[] ans = new int[n];5 Arrays.fill(ans, -1);6 7 TreeSet<Integer>[] unseen = new TreeSet[2];8 unseen[0] = new TreeSet<>();9 unseen[1] = new TreeSet<>();10 11 for (int num = 0; num < n; ++num)12 if (num != p && !bannedSet.contains(num))13 unseen[num % 2].add(num);14 15 16 Queue<Integer> q = new ArrayDeque<>(List.of(p));17 ans[p] = 0;18 19 while (!q.isEmpty()) {20 final int u = q.poll();21 final int lo = Math.max(u - k + 1, k - 1 - u);22 final int hi = Math.min(u + k - 1, n - 1 - (u - (n - k)));23 24 TreeSet<Integer> nums = unseen[lo % 2];25 for (Integer num = nums.ceiling(lo); num != null && num <= hi;) {26 ans[num] = ans[u] + 1;27 q.offer(num);28 nums.remove(num);29 num = nums.higher(num);30 }31 }32 33 return ans;34 }35}36