https://leetcode.com/problems/mirror-reflection

The idea of this problem, instead of reflecting our ray, we will look at it from the point of view of our ray, which is straight line: see the following image for better understanding.

image

How we can find what we need to return: 0, 1 or 2:

  1. If both number of reflections of our room are even, like in our image, we need to return 1.
  2. If horizontal line of reflections is odd and vertical is even, we need to return 0.
  3. If horizontal line of reflections is even and vertical is odd, we need to return 2.
  4. Note, that it can not happen that both number are even, than we have one angle before, if we divide these two numbers by 2.

Finally, all this can be written in oneliner as follow:

Complexity: time and space complexity is O(1) if we assume that we can find gcd in O(1) time (which is true for int32 numbers). If you want to be more mathematically correct, it is O(log n).

class Solution:
    def mirrorReflection(self, p, q):
        return (q//gcd(p,q)%2 - p//gcd(p,q)%2 + 1)

If you like the solution, you can upvote it on leetcode discussion section: Problem 0858