Mirror Reflection - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: p = 2, q = 1
Output: 2
💡 Note: The ray starts at (0,0) and first hits the east wall at (2,1). After bouncing, it eventually reaches receptor 2 at the northwest corner (0,2).
Example 2 — Different Path
$ Input: p = 3, q = 1
Output: 1
💡 Note: The ray bounces multiple times but eventually hits receptor 1 at the northeast corner (3,3).
Example 3 — Direct Hit
$ Input: p = 1, q = 1
Output: 1
💡 Note: The ray travels diagonally and directly hits receptor 1 at (1,1) without any bounces.

Constraints

  • 1 ≤ p ≤ 1000
  • 0 < q < p

Visualization

Tap to expand
Mirror Reflection Problem INPUT North Wall South Wall West East 1 0 2 Laser q=1 p = 2 p = 2 wall length q = 1 first hit Receptors: 0: SE corner 1: NE corner 2: NW corner SW: Laser ALGORITHM STEPS 1 Extend Room Virtually Unfold mirrors, stack rooms Straight line 2 Find LCM(p, q) LCM(2,1) = 2 3 Calculate Reflections m = LCM/p = 2/2 = 1 n = LCM/q = 2/1 = 2 4 Determine Receptor m=1 (odd), n=2 (even) m odd, n odd --> 1 m odd, n even --> 2 m=1(odd), n=2(even) m even, n odd --> 0 FINAL RESULT 1 0 2 Output: 2 OK Ray hits receptor 2 at NW corner after 1 reflection O(log(min(p,q))) Key Insight: Instead of simulating reflections, unfold the room by mirroring it repeatedly. The laser travels in a straight line. Find where it first hits a corner using LCM of p and q. The parity of m (vertical copies) and n (horizontal copies) determines which receptor is hit. TutorialsPoint - Mirror Reflection | Optimal Solution (Mathematical Approach)
Asked in
Google 15 Facebook 8
28.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen