#878

Nth Magical Number

Hard
MathBinary SearchBinary SearchMathematical Properties
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(log(n * min(a, b)))
Space
O(1)
O(1)
💡

Intuition

Time O(log(n * min(a, b)))Space O(1)

Instead of checking each number, we can use binary search to find the nth magical number more efficiently. We calculate the count of magical numbers up to a certain point and adjust our search range accordingly.

⚙️

Algorithm

5 steps
  1. 1Step 1: Calculate the least common multiple (LCM) of a and b.
  2. 2Step 2: Set the search range between 1 and n * min(a, b).
  3. 3Step 3: Use binary search to find the smallest number x such that the count of magical numbers up to x is at least n.
  4. 4Step 4: The count of magical numbers up to x is given by (x // a) + (x // b) - (x // lcm(a, b)).
  5. 5Step 5: Return the result modulo 10^9 + 7.
solution.py14 lines
1# Full working Python code
2import math
3
4def nthMagicalNumber(n, a, b):
5    mod = 10**9 + 7
6    lcm_ab = a * b // math.gcd(a, b)
7    left, right = 1, n * min(a, b)
8    while left < right:
9        mid = (left + right) // 2
10        if mid // a + mid // b - mid // lcm_ab < n:
11            left = mid + 1
12        else:
13            right = mid
14    return left % mod

Complexity note: The time complexity is O(log(n * min(a, b))) due to the binary search over the range. The space complexity is O(1) since we are using a constant amount of space.

  • 1Understanding the concept of LCM is crucial for optimizing the search for magical numbers.
  • 2Binary search can significantly reduce the time complexity compared to a brute-force approach.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.