Determine if a Cell Is Reachable at a Given Time — LeetCode 2849 Python Solution

MediumMath
Problem
#2849
Reading time
2 min

The problem

You are given four integers sx, sy, fx, fy, and a non-negative integer t. In an infinite 2D grid, you start at the cell (sx, sy).

Example

Input
sx = 2, sy = 4, fx = 7, fy = 7, t = 6
Output
true
Explanation
Starting at cell (2, 4), we can reach cell (7, 7) in exactly 6 seconds by going through the cells depicted in the picture above.

Python solution

Python
class Solution:
    def isReachableAtTime(self, sx: int, sy: int, fx: int, fy: int, t: int) -> bool:
        if sx == fx and sy == fy:
            return t != 1
        dx = abs(sx - fx)
        dy = abs(sy - fy)
        return max(dx, dy) <= t

Complexity

MeasureComplexity
TimeO(1)
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2849. Determine if a Cell Is Reachable at a Given Time is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2849. Determine if a Cell Is Reachable at a Given Time?
LeetCode 2849. Determine if a Cell Is Reachable at a Given Time is rated Medium on LeetCode.
What is the time complexity of LeetCode 2849. Determine if a Cell Is Reachable at a Given Time?
The Python solution on this page runs in O(1).
What is the space complexity of LeetCode 2849. Determine if a Cell Is Reachable at a Given Time?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2849. Determine if a Cell Is Reachable at a Given Time cover?
LeetCode 2849. Determine if a Cell Is Reachable at a Given Time is tagged Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview