Skip to content
Problem 789 · LeetCode 789(opens in a new tab)

Escape The Ghosts

MediumArrays

You start at (0, 0) on an endless square grid and want to reach the point target. Some ghosts start at the points in ghosts. On every turn you and every ghost each move one square up, down, left or right, or stay put, all at the same time.

You escape if you reach the target before any ghost can stand on the same square as you. Arriving anywhere, the target included, on the same turn as a ghost counts as being caught. Return true if you can escape no matter how the ghosts move, and false otherwise.

Example 1

Input:  ghosts = [[2, -1], [-3, 2]], target = [1, 1]
Output: true
Why:    you need 2 turns; the ghosts need 3 and 5
2 more examples and the constraints

Example 2

Input:  ghosts = [[3, 0]], target = [2, 1]
Output: false
Why:    the ghost needs 2 turns, you need 3

Example 3

Input:  ghosts = [[0, 4]], target = [1, 2]
Output: false
Why:    both need 3 turns, and a tie is a catch

Constraints

  • 1 ≤ number of ghosts ≤ 100
  • Every coordinate is between −10,000 and 10,000
  • Several ghosts may share a square

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Check every square of your pathO(g·d)
  2. Compare distances to the targetO(g)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100 ghosts and a far targetVerdict
Check every square of your pathO(g·d)
Correct, but walks the whole path
Compare distances to the targetO(g)
Best; one number per ghost

g = number of ghosts, d = your distance to the target.

Edge cases to test

  • A tie. A ghost exactly as far from the target as you means false.
  • Ghost behind you. [[-1, 0]] with target [3, 0]: the ghost needs 4 turns, you need 3, so true.
  • Ghost on the target. Its distance is 0, so you are caught: false.
  • Ghost on your start. It is as far from the target as you are: false.
  • Coordinates at the limit. Distances reach 40,000, well inside a 32-bit int.

Common mistakes

  • Using < instead of <=, so a ghost that arrives on the same turn lets you through.
  • Measuring each ghost's distance to you instead of to the target.
  • Using straight-line distance; moves are along the grid, so it is |dx| + |dy|.

How to talk through it

  1. 1Clarify. Does a tie count as a catch? Can ghosts stand still or share a square?
  2. 2Give the brute force. Walk one shortest path and check each square against each ghost.
  3. 3Find the key fact. A ghost that can cut you off can also wait at the target, so only the target matters.
  4. 4Code the one pass. Compute your distance once, then compare each ghost's distance with <=.
  5. 5Test out loud. Run a tie, a ghost on the target and a ghost behind you.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?