Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 878: Nth Magical Number

MathBinary Search

LeetCode 878 Solution Explanation

Explanation

To solve this problem, we can use the concept of binary search. We can find the least common multiple (LCM) of a and b and then use binary search to find the nth magical number within a range of [1, n * min(a, b)]. We can calculate the LCM using the formula LCM(a, b) = a * b / GCD(a, b) where GCD is the greatest common divisor. Once we have the LCM, we can find how many magical numbers are there in each interval of length LCM. Using binary search, we can efficiently find the nth magical number.

LeetCode 878 Solutions in Java, C++, Python

class Solution {
    public int nthMagicalNumber(int n, int a, int b) {
        long mod = 1000000007;
        long lcm = a / gcd(a, b) * b;
        long low = 1, high = (long)1e18;
        
        while (low < high) {
            long mid = low + (high - low) / 2;
            long count = mid / a + mid / b - mid / lcm;
            
            if (count < n) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        
        return (int)(low % mod);
    }
    
    private long gcd(long a, long b) {
        if (b == 0) return a;
        return gcd(b, a % b);
    }
}

Interactive Code Editor for LeetCode 878

Improve Your LeetCode 878 Solution

Use the editor below to refine the provided solution for LeetCode 878. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems