LeetCode 1201: Ugly Number III Solution
Master LeetCode problem 1201 (Ugly Number III), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1201. Ugly Number III
Problem Explanation
Explanation:
To solve this problem, we can use the concept of least common multiple (LCM) and binary search. We need to find the nth ugly number that is divisible by a, b, or c. We can take advantage of the fact that the LCM of a, b, and c will give us the period at which the next ugly number is generated.
- We first find the LCM of a, b, and c.
- Then, using binary search, we find the nth ugly number within the range of 1 to 2 * 10^9.
- In the binary search process, we calculate the number of ugly numbers that are less than or equal to the mid value.
- Based on this count, we adjust the search space to find the nth ugly number. :
Solution Code
class Solution {
public int nthUglyNumber(int n, int a, int b, int c) {
long lcmAB = lcm(a, b);
long lcmBC = lcm(b, c);
long lcmAC = lcm(a, c);
long lcmABC = lcm(lcmAB, c);
long left = 1, right = Long.MAX_VALUE;
while (left < right) {
long mid = left + (right - left) / 2;
long count = mid / a + mid / b + mid / c - mid / lcmAB - mid / lcmBC - mid / lcmAC + mid / lcmABC;
if (count < n) {
left = mid + 1;
} else {
right = mid;
}
}
return (int)left;
}
private long lcm(long a, long b) {
return a * b / gcd(a, b);
}
private long gcd(long a, long b) {
while (b != 0) {
long temp = b;
b = a % b;
a = temp;
}
return a;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1201 (Ugly Number III)?
This page provides optimized solutions for LeetCode problem 1201 (Ugly Number III) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1201 (Ugly Number III)?
The time complexity for LeetCode 1201 (Ugly Number III) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1201 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1201 in Java, C++, or Python.