![]() |
VOOZH | about |
Given four integers X1, Y1, X2, and Y2, the task is to check if it is possible to convert the point (X1, Y1) to the point (X2, Y2) through some operations. The allowed operations on some point (X, Y) are to convert it to either (X, X+ Y) or (X + Y, Y).
Examples:
Input: X1 = 1, Y1 = 1, X2 = 3, Y2 = 5
Output: true
Explanation: One series of moves that transforms the starting point to the target is:
- (1, 1) -> (1, 2)
- (1, 2) -> (3, 2)
- (3, 2) -> (3, 5)
Input: X1 = 1, Y1 = 1, X2 = 2, Y2 = 2
Output: false
Explanation: It is not possible to convert (1, 1) to (2, 2) using the allowed operations.
Approach:
To determine whether it is possible to convert (X1, Y1) to (X2, Y2) using the allowed operations, we can reverse the problem. Instead of trying to build up from (X1, Y1) to (X2, Y2), we can work backwards from (X2, Y2) to (X1, Y1) using the inverse operations:
- From (X, Y), if X >= Y, we can go back to (X - Y, Y).
- If Y >= X, we can go back to (X, Y - X).
This reversal approach helps us efficiently check if we can reduce (X2, Y2) back to (X1, Y1).
Steps-by-step approach:
Below is the implementation of the above approach:
true
Time Complexity: The while loop iterates as long as X2 > X1 and Y2 > Y1. In each iteration, the larger of X2 or Y2 is reduced by taking the modulo with the smaller one, which can be considered as logarithmic reduction in the worst case. Hence, the time complexity is approximately O(log max(X2,Y2)).
Auxiliary Space: O(1) as we are using a constant amount of extra space regardless of the input size.