|
| 1 | +# 2543. Check if Point Is Reachable |
| 2 | +# 🔴 Hard |
| 3 | +# |
| 4 | +# https://leetcode.com/problems/check-if-point-is-reachable/ |
| 5 | +# |
| 6 | +# Tags: Greedy - Dynamic Programming - Math |
| 7 | + |
| 8 | +import timeit |
| 9 | +from math import gcd |
| 10 | + |
| 11 | + |
| 12 | +# Simulate the movements that are allowed but in reverse, starting at |
| 13 | +# the target point and trying to reach (1, 1). |
| 14 | +# |
| 15 | +# Time complexity: O(log(max(m, n))) - At each step we divide by 2 |
| 16 | +# approximately, if one of the values is not divisible one loop, it will |
| 17 | +# became divisible in the next loop. |
| 18 | +# Space complexity: O(1) - We only store two integers and one tuple with |
| 19 | +# two elements. |
| 20 | +# |
| 21 | +# Runtime 33 ms Beats 100% |
| 22 | +# Memory 13.9 MB Beats 33.33% |
| 23 | +class GreedySimulation: |
| 24 | + def isReachable(self, targetX: int, targetY: int) -> bool: |
| 25 | + last, x, y = (-1, -1), targetX, targetY |
| 26 | + # While we make progress and have not matched the start. |
| 27 | + while (x, y) != last: |
| 28 | + if x == 1 and y == 1: |
| 29 | + return True |
| 30 | + last = (x, y) |
| 31 | + if x % 2 == 0: |
| 32 | + x //= 2 |
| 33 | + if y % 2 == 0: |
| 34 | + y //= 2 |
| 35 | + if x > y: |
| 36 | + x -= y |
| 37 | + if x < y: |
| 38 | + y -= x |
| 39 | + return False |
| 40 | + |
| 41 | + |
| 42 | +# Great solutions using the greater common divisor in the discuss |
| 43 | +# section. I liked one by lee215 in particular. |
| 44 | +# https://leetcode.com/problems/check-if-point-is-reachable/solutions/3082073 |
| 45 | +# |
| 46 | +# Time complexity: O(log(m) + log(y)) |
| 47 | +# Space complexity: O(1) |
| 48 | +# |
| 49 | +# Runtime 35 ms Beats 88.89% |
| 50 | +# Memory 13.8 MB Beats 44.44% |
| 51 | +class GCDPoT: |
| 52 | + def isReachable(self, targetX: int, targetY: int) -> bool: |
| 53 | + mcd = gcd(targetX, targetY) |
| 54 | + return mcd == mcd & -mcd |
| 55 | + |
| 56 | + |
| 57 | +def test(): |
| 58 | + executors = [ |
| 59 | + GreedySimulation, |
| 60 | + GCDPoT, |
| 61 | + ] |
| 62 | + tests = [ |
| 63 | + [6, 9, False], |
| 64 | + [4, 7, True], |
| 65 | + ] |
| 66 | + for executor in executors: |
| 67 | + start = timeit.default_timer() |
| 68 | + for _ in range(1): |
| 69 | + for col, t in enumerate(tests): |
| 70 | + sol = executor() |
| 71 | + result = sol.isReachable(t[0], t[1]) |
| 72 | + exp = t[2] |
| 73 | + assert result == exp, ( |
| 74 | + f"\033[93m» {result} <> {exp}\033[91m for" |
| 75 | + + f" test {col} using \033[1m{executor.__name__}" |
| 76 | + ) |
| 77 | + stop = timeit.default_timer() |
| 78 | + used = str(round(stop - start, 5)) |
| 79 | + cols = "{0:20}{1:10}{2:10}" |
| 80 | + res = cols.format(executor.__name__, used, "seconds") |
| 81 | + print(f"\033[92m» {res}\033[0m") |
| 82 | + |
| 83 | + |
| 84 | +test() |
0 commit comments