Determine if a Cell Is Reachable at a Given Time - Greedy O(1) [JS]

Description 

Solution: Greedy

The minimum time from (sx, sy) to (fx, fy) is max(diff x, diff y).
If the minimum time is less than or equal to t, it's always possible to reach it in exactly t moves because we can spend excess moves hopping around the target cell.

The only case where this isn't true is when the two cells start off at the same position and t is 1.
We have no choice but to leave the cell and don't have any time to come back.

Time Complexity: O(1)
Space Complexity: O(1)

var isReachableAtTime = function(sx, sy, fx, fy, t) {
  if (sx === fx && sy === fy && t === 1) return false;
  let diffX = Math.abs(sx - fx), diffY = Math.abs(sy - fy);
  return Math.max(diffX, diffY) <= t;
};

Comments

Popular posts from this blog

Beautiful Towers II - Monotonic Increasing Stack [JS]

Check if There is a Valid Partition For The Array - Two Approaches - DP & Recursion w/ Memoization [JS]

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Count Elements With Maximum Frequency - Hashmap [JS]

Divide Nodes Into the Maximum Number of Groups - Union Find & BFS [JS]