878. Nth Magical Number LeetCode Solution

In this guide, you will get 878. Nth Magical Number LeetCode Solution with the best time and space complexity. The solution to Nth Magical Number 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. Nth Magical Number solution in C++
  4. Nth Magical Number solution in Java
  5. Nth Magical Number solution in Python
  6. Additional Resources
878. Nth Magical Number LeetCode Solution image

Problem Statement of Nth Magical Number

A positive integer is magical if it is divisible by either a or b.
Given the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7.

Example 1:

Input: n = 1, a = 2, b = 3
Output: 2

Example 2:

Input: n = 4, a = 2, b = 3
Output: 6

Constraints:

1 <= n <= 109
2 <= a, b <= 4 * 104

Complexity Analysis

  • Time Complexity: O(\log(\min(A, B) \cdot n))
  • Space Complexity: O(1)

878. Nth Magical Number LeetCode Solution in C++

class Solution {
 public:
  int nthMagicalNumber(long n, long a, long b) {
    constexpr int kMod = 1'000'000'007;
    const long lcm = a * b / __gcd(a, b);
    long l = min(a, b);
    long r = min(a, b) * n;

    while (l < r) {
      const long m = (l + r) / 2;
      if (m / a + m / b - m / lcm >= n)
        r = m;
      else
        l = m + 1;
    }

    return l % kMod;
  }
};
/* code provided by PROGIEZ */

878. Nth Magical Number LeetCode Solution in Java

class Solution {
  public int nthMagicalNumber(long n, long a, long b) {
    final int kMod = 1_000_000_007;
    final long lcm = a * b / gcd(a, b);
    long l = Math.min(a, b);
    long r = Math.min(a, b) * n;

    while (l < r) {
      final long m = (l + r) / 2;
      if (m / a + m / b - m / lcm >= n)
        r = m;
      else
        l = m + 1;
    }

    return (int) (l % kMod);
  }

  private long gcd(long a, long b) {
    return b == 0 ? a : gcd(b, a % b);
  }
}
// code provided by PROGIEZ

878. Nth Magical Number LeetCode Solution in Python

class Solution:
  def nthMagicalNumber(self, n: int, a: int, b: int) -> int:
    lcm = a * b // math.gcd(a, b)
    l = min(a, b)
    r = min(a, b) * n
    ans = bisect.bisect_left(range(l, r), n,
                             key=lambda m: m // a + m // b - m // lcm) + l
    return ans % (10**9 + 7)
# code by PROGIEZ

Additional Resources

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