#3001

Minimum Moves to Capture The Queen

Medium
MathEnumerationTwo PointersSliding Window
LeetCode ↗

Approaches

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

Intuition

Time O(1)Space O(1)

The optimal solution leverages the properties of chess pieces to determine if the rook or bishop can capture the queen in one move, or if they need to reposition first. This reduces unnecessary checks and calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Check if the rook can capture the queen in one move (same row or column).
  2. 2Step 2: Check if the bishop can capture the queen in one move (same diagonal).
  3. 3Step 3: If neither can capture directly, check if they can move to a position that allows them to capture the queen in the next move.
solution.py6 lines
1def min_moves_to_capture(a, b, c, d, e, f):
2    if (a == e or b == f) and not ((a == e and (b < f < d or d < f < b)) or (b == f and (a < e < c or c < e < a))):
3        return 1
4    if abs(a - e) == abs(b - f) and not ((a < e < c or c < e < a) and (b < f < d or d < f < b)):
5        return 1
6    return 2

Complexity note: The time complexity is O(1) because we are only performing a fixed number of checks, regardless of the board size.

  • 1The rook and bishop can capture the queen in one move if there are no pieces blocking their path.
  • 2If they cannot capture in one move, they can often reposition to capture in two moves.

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