910. Nth Magical Number
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the nth "magical number," where a magical number is a positive integer divisible by a or b. The sequence of magical numbers is sorted. Since n can be very large (up to (10^9)), we cannot generate these numbers one by one. This suggests that a mathematical or search-based approach is needed.
Solution
Nth Magical Number in Python
import math
class Solution:
def nthMagicalNumber(self, n: int, a: int, b: int) -> int:
# Define the modulo constant
MOD = 10**9 + 7
# Calculate the least common multiple (LCM)
l = (a * b) // math.gcd(a, b)
# Binary search for the nth magical number
low = 1
# A safe upper bound for the nth magical number is n * min(a, b)
high = n * min(a, b)
ans = 0
while low <= high:
mid = (low + high) // 2
# Count magical numbers up to mid using the Principle of Inclusion-Exclusion
count = mid // a + mid // b - mid // l
if count >= n:
# mid is a potential answer, try to find a smaller one
ans = mid
high = mid - 1
else:
# mid is too small, need to search in the higher range
low = mid + 1
# The answer is the smallest number 'ans' such that count(ans) >= n
# Return the result modulo 10^9 + 7
return ans % MOD
Nth Magical Number in Java
class Solution {
public int nthMagicalNumber(int n, int a, int b) {
// Define the modulo constant
long MOD = 1_000_000_007;
// Use long for intermediate calculations to prevent overflow
long N = n;
long A = a;
long B = b;
// Calculate the least common multiple (LCM)
long L = (A * B) / gcd(A, B);
// Binary search for the nth magical number
long low = 1;
// A safe upper bound for the nth magical number is n * min(a, b)
long high = N * Math.min(A, B);
long ans = 0;
while (low <= high) {
long mid = low + (high - low) / 2;
// Count magical numbers up to mid using the Principle of Inclusion-Exclusion
long count = mid / A + mid / B - mid / L;
if (count >= N) {
// mid is a potential answer, try to find a smaller one
ans = mid;
high = mid - 1;
} else {
// mid is too small, need to search in the higher range
low = mid + 1;
}
}
// The answer is the smallest number 'ans' such that count(ans) >= n
// Return the result modulo 10^9 + 7
return (int)(ans % MOD);
}
// Helper function to calculate the greatest common divisor (GCD)
private long gcd(long x, long y) {
while (y > 0) {
long temp = x % y;
x = y;
y = temp;
}
return x;
}
}
Nth Magical Number in C++
class Solution {
public:
int nthMagicalNumber(int n, int a, int b) {
// Define the modulo constant
long long MOD = 1e9 + 7;
// Use long long for intermediate calculations to prevent overflow
long long N = n;
long long A = a;
long long B = b;
// Calculate the least common multiple (LCM)
long long L = (A * B) / gcd(A, B);
// Binary search for the nth magical number
long long low = 1;
// A safe upper bound for the nth magical number is n * min(a, b)
long long high = N * std::min(A, B);
long long ans = 0;
while (low <= high) {
long long mid = low + (high - low) / 2;
// Count magical numbers up to mid using the Principle of Inclusion-Exclusion
long long count = mid / A + mid / B - mid / L;
if (count >= N) {
// mid is a potential answer, try to find a smaller one
ans = mid;
high = mid - 1;
} else {
// mid is too small, need to search in the higher range
low = mid + 1;
}
}
// The answer is the smallest number 'ans' such that count(ans) >= n
// Return the result modulo 10^9 + 7
return ans % MOD;
}
private:
// Helper function to calculate the greatest common divisor (GCD)
long long gcd(long long x, long long y) {
while (y) {
x %= y;
std::swap(x, y);
}
return x;
}
};
Nth Magical Number in TypeScript
/**
* Helper function to calculate the greatest common divisor (GCD)
*/
function gcd(x: number, y: number): number {
while (y) {
[x, y] = [y, x % y];
}
return x;
}
function nthMagicalNumber(n: number, a: number, b: number): number {
// Define the modulo constant
const MOD = 1e9 + 7;
// Calculate the least common multiple (LCM)
// JavaScript numbers are 64-bit floats, which can handle the intermediate values.
const l = (a * b) / gcd(a, b);
// Binary search for the nth magical number
let low = 1;
// A safe upper bound for the nth magical number is n * min(a, b)
let high = n * Math.min(a, b);
let ans = 0;
while (low <= high) {
// Use Math.floor to ensure mid is an integer
let mid = Math.floor(low + (high - low) / 2);
// Count magical numbers up to mid using the Principle of Inclusion-Exclusion
// Use Math.floor for integer division
let count = Math.floor(mid / a) + Math.floor(mid / b) - Math.floor(mid / l);
if (count >= n) {
// mid is a potential answer, try to find a smaller one
ans = mid;
high = mid - 1;
} else {
// mid is too small, need to search in the higher range
low = mid + 1;
}
}
// The answer is the smallest number 'ans' such that count(ans) >= n
// Return the result modulo 10^9 + 7
return ans % MOD;
};
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.