Problem 789

Abstract / Summary

You must reach a target before any ghost can get there from their starting position.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0789.py

class Solution:
    def escapeGhosts(self, ghosts: List[List[int]], target: List[int]) -> bool:
        def distance(x, y):
            return abs(target[0] - x) + abs(target[1] - y)

        return all(distance(g[0], g[1]) > distance(0, 0) for g in ghosts)
6 lines | 264 bytes | submitted October 24, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 64% (60k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method escapeGhosts. The method receives a list of ghost positions and a target coordinate, then decides whether a player starting at the origin can reach the target before any ghost can intercept. The core logic relies on Manhattan distance calculations and a short-circuiting all check.

Key Steps

The first important step is the definition of a helper function that computes the Manhattan distance from any point to the target.

def distance(x, y):
    return abs(target[0] - x) + abs(target[1] - y)

This function is used twice: once to evaluate the player’s distance from the origin and repeatedly for each ghost’s distance to the target.

The second critical step is the single return statement that aggregates the comparison for all ghosts.

return all(distance(g[0], g[1]) > distance(0, 0) for g in ghosts)

The generator expression iterates over each ghost coordinate g, computes its distance to the target, and checks whether it exceeds the player’s distance from the origin. The all built-in yields True only if every ghost satisfies the strict inequality.

Edge Cases Handled

When the list of ghosts is empty, the generator expression produces no elements. In Python, all on an empty iterable returns True, meaning the player can always reach the target when no ghosts are present.

If a ghost occupies the same position as the target, the distance from that ghost to the target evaluates to zero. Since the player’s distance is non-negative, the strict > comparison fails, correctly indicating that the player cannot escape.

When a ghost is located at the origin, its distance to the target equals the player’s distance. The strict inequality ensures that a tie results in a False outcome, reflecting the rule that a simultaneous arrival does not constitute a safe escape.

Negative coordinates for either ghosts or the target are processed without issue because the abs function normalizes the differences, preserving the correctness of Manhattan distance in all quadrants.

Large integer values are handled gracefully because the arithmetic operations remain within Python’s arbitrary-precision integer domain, preventing overflow concerns.

Performance Optimizations

The implementation defines the distance helper locally inside the method, allowing the function to capture the target variable without passing it explicitly each time. This reduces parameter passing overhead for each distance calculation.

The use of a generator expression inside all provides short-circuit evaluation: as soon as a ghost is found whose distance is not greater than the player’s, the iteration stops and the method returns False. This avoids unnecessary distance computations for remaining ghosts.

Relying on built-in functions such as abs and the all construct leverages highly optimized C-level implementations, contributing to faster execution compared to manual loops.

No auxiliary data structures (e.g., lists or dictionaries) are created during the process, keeping memory usage minimal and avoiding extra allocation costs.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you are playing a game of tag on a giant grid drawn on the floor with chalk. You want to reach a special spot marked as the target. There are ghosts also moving around on this same grid.

To see if you can reach the target safely, you need to measure the distance from where you are standing to the target. In this game, distance is measured by counting how many squares you walk sideways and how many you walk forward.

The code looks at every ghost and measures how far each ghost is from the target. It also measures how far you are from the target starting from the very center of the grid.

If your distance to the target is smaller than the distance every single ghost has to travel to reach that same spot, you can win the race. Even if just one ghost is closer to the target than you are, it will get there first. This code checks all those distances to see if you can make it to your goal before any of the ghosts do.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.93 | σ = 1.49

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
JoshCrozier JS
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
JoshCrozier JavaScript
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
zfang399 C++
28 links | 15 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

1 easy 7 medium 1 hard
10 solutions   October 24, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality