Mirror Reflection — LeetCode 858 Python Solution

MediumGeometryMathNumber Theory
Problem
#858
Reading time
2 min

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

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

Complexity

MeasureComplexity
TimeO(n) or O(1)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview