Leetcode 858. Mirror Reflection
858. Mirror Reflection
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.
The square room has walls of length p
and a laser ray from the southwest corner first meets the east wall at a distance q
from the 0th receptor. The laser ray continues to bounce off the east and north walls until it eventually meets a receptor.
Return the number of the receptor that the laser ray will meet first.
Example 1:
Input: p = 2, q = 1
Output: 2
Explanation: The ray meets receptor 2 first after bouncing off the east wall and the north wall.
Example 2:
Input: p = 3, q = 1
Output: 1
Note:
1 <= p <= 1000
0 <= q <= p
public class Solution {
public int mirrorReflection(int p, int q) {
int m = q, n = p;
while (m % 2 == 0 && n % 2 == 0) {
m /= 2;
n /= 2;
}
if (m % 2 == 0 && n % 2 != 0) {
return 0; // hitting receptor 0
}
if (m % 2 != 0 && n % 2 != 0) {
return 1; // hitting receptor 1
}
if (m % 2 != 0 && n % 2 == 0) {
return 2; // hitting receptor 2
}
return -1; // this line theoretically should not be reached
}
}
p x p
.m*p
or n*q
aligns perfectly with the cells.m
and n
such that m*q = n*p
.p
and q
via the Euclidean algorithm (GCD).m/n
and check the parity (even or odd) values:
n
is odd and m
is even, the laser hits receptor 0.m
and n
are odd, the laser hits receptor 1.n
is even and m
is odd, the laser hits receptor 2.The time complexity is primarily determined by the while loop which divides by 2 until one of the numbers is odd. This loop is logarithmic with respect to p
and q
, hence the complexity is O(log(min(p, q)))
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?