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)
Difficulty
and has an acceptance rate of about 64% (60k+ submissions).
Typical patterns to solve this problem:
- Array
- Math
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Solved On The Same Day
- problem 884: Uncommon Words from Two Sentences
- problem 781: Rabbits in Forest
- problem 817: Linked List Components
- problem 822: Card Flipping Game
- problem 840: Magic Squares In Grid
- problem 861: Score After Flipping Matrix
- problem 870: Advantage Shuffle
- problem 904: Fruit Into Baskets
- problem 745: Prefix and Suffix Search
Extra
- 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