#789

Escape The Ghosts

Medium
ArrayMathDistance CalculationGrid Traversal
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

The optimal solution is essentially the same as the brute-force approach but emphasizes the efficiency of checking distances directly, ensuring we minimize unnecessary calculations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the Manhattan distance from the starting point [0, 0] to the target [x_target, y_target].
  2. 2Step 2: Initialize a variable to track the player's distance to the target.
  3. 3Step 3: For each ghost, calculate its distance to the target and compare it with the player's distance.
  4. 4Step 4: If any ghost's distance is less than or equal to the player's distance, return false. Otherwise, return true.
solution.py3 lines
1def escapeGhosts(ghosts, target):
2    player_distance = abs(target[0]) + abs(target[1])
3    return all(abs(ghost[0] - target[0]) + abs(ghost[1] - target[1]) > player_distance for ghost in ghosts)

Complexity note: The time complexity remains O(n) as we still iterate through each ghost, and the space complexity is O(1) since we only store a few variables.

  • 1The distance metric used is Manhattan distance, which is suitable for grid-based movement.
  • 2Simultaneous movement means we need to consider the worst-case scenario for the ghosts.

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