858. Mirror Reflection LeetCode Solution

In this guide, you will get 858. Mirror Reflection LeetCode Solution with the best time and space complexity. The solution to Mirror Reflection problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Mirror Reflection solution in C++
  4. Mirror Reflection solution in Java
  5. Mirror Reflection solution in Python
  6. Additional Resources
858. Mirror Reflection LeetCode Solution image

Problem Statement of Mirror Reflection

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.

Example 1:

Input: p = 2, q = 1
Output: 2
Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.

Example 2:

Input: p = 3, q = 1
Output: 1

Constraints:

1 <= q <= p <= 1000

Complexity Analysis

  • Time Complexity: O(\log p)
  • Space Complexity: O(1)

858. Mirror Reflection LeetCode Solution in C++

class Solution {
 public:
  int mirrorReflection(int p, int q) {
    while (p % 2 == 0 && q % 2 == 0) {
      p /= 2;
      q /= 2;
    }

    if (p % 2 == 0)
      return 2;
    if (q % 2 == 0)
      return 0;
    return 1;
  }
};
/* code provided by PROGIEZ */

858. Mirror Reflection LeetCode Solution in Java

class Solution {
  public int mirrorReflection(int p, int q) {
    while (p % 2 == 0 && q % 2 == 0) {
      p /= 2;
      q /= 2;
    }

    if (p % 2 == 0)
      return 2;
    if (q % 2 == 0)
      return 0;
    return 1;
  }
}
// code provided by PROGIEZ

858. Mirror Reflection LeetCode Solution in Python

class Solution:
  def mirrorReflection(self, p: int, q: int) -> int:
    while p % 2 == 0 and q % 2 == 0:
      p //= 2
      q //= 2

    if p % 2 == 0:
      return 2
    if q % 2 == 0:
      return 0
    return 1
# code by PROGIEZ

Additional Resources

See also  2529. Maximum Count of Positive Integer and Negative Integer LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.