Mirror Reflection — LeetCode 858 Python Solution
- Problem
- #858
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- p = 2, q = 1
- Output
- 2
- Explanation
- The ray meets receptor 2 the first time it gets reflected back to the left wall.
Python solution
class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
g = gcd(p, q)
p = (p // g) % 2
q = (q // g) % 2
if p == 1 and q == 1:
return 1
return 0 if p == 1 else 2Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) or O(1) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 858. Mirror Reflection is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math, Number Theory and Geometry.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 858. Mirror Reflection?
- LeetCode 858. Mirror Reflection is rated Medium on LeetCode.
- What topics does LeetCode 858. Mirror Reflection cover?
- LeetCode 858. Mirror Reflection is tagged Geometry, Math and Number Theory on LeetCode.