#2612

Minimum Reverse Operations

Hard
ArrayHash TableBreadth-First SearchUnion-FindOrdered SetBreadth-First SearchGraph Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a breadth-first search (BFS) approach allows us to explore all possible positions of the 1 efficiently. We can treat each position as a node and the valid operations as edges, ensuring we find the shortest path to each position.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a queue for BFS and a visited set to track positions we've already processed.
  2. 2Step 2: Start from position p, mark it as visited, and enqueue it with 0 operations.
  3. 3Step 3: While the queue is not empty, dequeue a position and check all possible positions reachable by reversing subarrays of size k.
  4. 4Step 4: If a reachable position is not banned or visited, mark it, record the operation count, and enqueue it.
solution.py21 lines
1from collections import deque
2
3def minReverseOperations(n, p, banned, k):
4    banned_set = set(banned)
5    answer = [-1] * n
6    answer[p] = 0
7    queue = deque([p])
8    visited = set([p])
9
10    while queue:
11        current = queue.popleft()
12        for i in range(max(0, current - k + 1), min(n - k + 1, current + 1)):
13            if any(pos in banned_set for pos in range(i, i + k)):
14                continue
15            next_pos = i + k - 1 - (current - i)
16            if next_pos < 0 or next_pos >= n or next_pos in visited:
17                continue
18            visited.add(next_pos)
19            answer[next_pos] = answer[current] + 1
20            queue.append(next_pos)
21    return answer

Complexity note: The BFS explores each position at most once, leading to linear time complexity. The space complexity is due to the queue and visited set.

  • 1Banned positions restrict movement, making some targets unreachable.
  • 2Reversing a subarray can significantly change the position of the 1.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.