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

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]