There is a special square room with mirrors on each of the four walls. Except for the southeast corner, there are receptors in each corner of the room. 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 south wall.
Given the two integers p
and q
, return the number of the receptor that the ray meets first. The square room has four different corner receptors:
0
is on the southwest corner,1
is on the southeast corner,2
is on the northeast corner,3
is on the northwest corner (does not appear in the problem’s description, but implied by the problem’s constraints).The laser ray follows the rule of reflection: when it hits a wall, it will reflect back, just like a light ray bouncing off a mirror.
Q: Are p
and q
always positive integers?
A: Yes, p
and q
are always positive.
Q: Will the laser ever hit the southeast corner (receptor 1
)?
A: The problem implies that the laser can hit receptors 0
, 1
, or 2
. Receptor 3
(northwest corner) is not considered for returning results.
To solve the problem, consider how the ray will travel and reflect within the room. Instead of simulating the reflections directly in the physical room, we can think of the room being tiled infinitely in a grid of p x p
squares. This way, the ray’s path becomes a straight line, and the challenge reduces to finding how many “rooms” the ray crosses before hitting a receptor.
kp
where k
is a positive integer, and it will hit the east edge at x-coordinates kp / q
.p
and q
.
LCM(p, q) / q
p-length rooms horizontallyLCM(p, q) / p
q-length rooms vertically.1
2
import math
def mirrorReflection(p: int, q: int) -> int:
lcm = (p * q) // math.gcd(p, q)
# How many p lengths the laser travels to go directly along the east-west direction as integer p
m = lcm // q # Number of q-length vertical room boundaries crossed
n = lcm // p # Number of p-length horizontal room boundaries crossed
if m % 2 == 0 and n % 2 == 1:
return 0
elif m % 2 == 1 and n % 2 == 1:
return 1
elif m % 2 == 1 and n % 2 == 0:
return 2
# Example Usage:
p = 2
q = 1
print(mirrorReflection(p, q)) # Output: 2
Time Complexity: O(log(min(p, q))), mainly due to the gcd calculation.
The math.gcd
function runs in logarithmic time relative to the smaller of p
and q
. All other operations (multiplication, division, and modulus) are constant time.
The provided solution leverages mathematical manipulations to avoid the overhead of simulating ray reflections physically, making it efficient and scalable.
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?