#858
Medium Algorithms Mirror reflection
Math Geometry Number Theory
61.9% acceptance
Feb 22, 2026
1151
2561
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.
Given the two integers p and q, return the number of the receptor that the ray meets first.
The test cases are guaranteed so that the ray will meet a receptor eventually.
Solution
Rust
Time O(2^n)
Space O(n)
/*
* 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.
* Given the two integers p and q, return the number of the receptor that the ray meets first.
* The test cases are guaranteed so that the ray will meet a receptor eventually.
* Example 1:
* Input: p = 2, q = 1
* Output: 2
* Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.
* Example 2:
* Input: p = 3, q = 1
* Output: 1
* Constraints:
* 1 <= q <= p <= 1000
*/
impl Solution {
pub fn mirror_reflection(p: i32, q: i32) -> i32 {
fn gcd(a: i32, b: i32) -> i32 { if b == 0 { a } else { gcd(b, a % b) } }
let g = gcd(p, q);
let m = p / g; // number of "bounces" in terms of p
let n = q / g; // number of "bounces" in terms of q
if n % 2 == 0 { 0 }
else if m % 2 == 0 { 2 }
else { 1 }
}
}