Leetcode 858. Mirror Reflection
You are given a two-dimensional square room of size p x p
and a laser ray that starts from the corner (0, 0)
and runs diagonally in the direction of (p, p)
. There are mirrors on the walls of the room. The laser ray reflects off the mirrors until it finally hits a receptor at one of the corners of the room.
There are three receptors in the room as follows:
(p, 0)
(p, p)
(0, p)
Your task is to determine which receptor the laser ray will meet first. The square room has a symmetric property where the laser can reflect in different patterns. Given the side length p
of the square and the distance q
the laser first travels vertically to the opposite wall, return the number 0
, 1
, or 2
corresponding to which receptor the laser will meet first.
p
always a positive integer?q
always a positive integer and less than or equal to p
?(Assuming yes to all questions as they are typical constraints for such problems.)
p x p
squares. The point (m*p, n*p)
where the laser ray lands after reflections can be determined by tracking multiples of p
.p
and q
to determine when the ray hits the edge.Steps:
m
and n such that
mp and
nq` are the first common points.m
and n
are even or odd:
Equation:
m*p
and n*q
are equal.#include <iostream>
#include <algorithm> // for std::gcd
class Solution {
public:
int mirrorReflection(int p, int q) {
int gcd_pq = std::gcd(p, q);
int lcm_pq = (p * q) / gcd_pq;
int m = lcm_pq / p;
int n = lcm_pq / q;
if (m % 2 == 0 && n % 2 == 1) {
return 0;
} else if (m % 2 == 1 && n % 2 == 1) {
return 1;
} else if (m % 2 == 1 && n % 2 == 0) {
return 2;
}
return -1; // Just a safe return; the problem's nature should never hit this case.
}
};
int main() {
Solution solution;
std::cout << solution.mirrorReflection(2, 1) << std::endl; // Output: 2
std::cout << solution.mirrorReflection(3, 1) << std::endl; // Output: 1
return 0;
}
Thus, the overall time complexity is O(log(min(p, q))) due to the GCD calculation.
This code computes which receptor will be the first one the ray meets by considering the laser reflections’ properties and geometry within a room.
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?