Sponsored
Sponsored
This approach leverages binary search to efficiently find the nth magical number by examining the number of magical numbers <= mid value repeatedly until we find the nth one. Calculating the Least Common Multiple (LCM) of 'a' and 'b' helps in determining magical numbers.
Time Complexity: O(log(N * min(a, b)))
Space Complexity: O(1)
1class Solution:
2 def nthMagicalNumber(self, n, a, b):
3 def gcd(x, y):
4 while y:
5 x, y = y, x % y
6 return x
7
8 def lcm(x, y):
9 return x * y // gcd(x, y)
10
11 LCM = lcm(a, b)
12 low, high = 2, n * min(a, b)
13 MOD = 10**9 + 7
14
15 while low < high:
16 mid = (low + high) // 2
17 if (mid // a + mid // b - mid // LCM) < n:
18 low = mid + 1
19 else:
20 high = mid
21 return low % MOD
22
23# Example usage:
24sol = Solution()
25print(sol.nthMagicalNumber(4, 2, 3))
26
In Python, the solution uses the binary search pattern efficiently within a while loop. Employing floor division ensures integers are handled correctly, while the counting of magical numbers utilizes the properties of GCD and LCM to adjust the range of the search space effectively.
This approach involves generating magical numbers using a min-heap to simulate the generation process by pushing candidates generated by multiplying a set of base magical numbers with 'a' and 'b'. The minimum is repeatedly extracted until the nth magical number is found.
Time Complexity: O(n log n)
Space Complexity: O(n)
1import heapq
2
3def nthMagicalNumber(n, a, b):
4
The Python implementation uses a min-heap to manage and produce candidates for the magical numbers by systematically adding increments of 'a' and 'b'. The heap automatically keeps this collection sorted with respect to numerical magnitude, achieving efficient extraction. It ensures that duplicates (i.e., the same number coming from both sequences) are managed via conditions if a number is divisible by the increment.