algoadvance

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:

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.

Clarifying Questions:

  1. Q: Are p and q always positive integers? A: Yes, p and q are always positive.

  2. 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.

Strategy:

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.

  1. Concepts to Consider:
    • The ray’s path can be extended as a straight line in this conceptual infinite grid.
    • The line will hit the north edge at y-coordinates kp where k is a positive integer, and it will hit the east edge at x-coordinates kp / q.
  2. Calculate Reflection Number: Consider the least common multiple (LCM) of p and q.
    • The ray would hit the vertical wall when it travels a distance LCM(p, q) / q p-length rooms horizontally
    • It would hit the horizontal wall when it travels a distance LCM(p, q) / p q-length rooms vertically.
  3. Determine the Receptor:
    • If the number of rooms horizontally is odd => receptor 1
    • If the number of rooms vertically is even => receptor 2

Code:

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:

The provided solution leverages mathematical manipulations to avoid the overhead of simulating ray reflections physically, making it efficient and scalable.

Try our interview co-pilot at AlgoAdvance.com