Leetcode 1201: Ugly Number III

grid47
grid47
Exploring patterns and algorithms
Jul 9, 2024 6 min read

An ugly number is a positive integer that is divisible by at least one of the integers a, b, or c. Your task is to return the nth ugly number in the sequence formed by the integers divisible by a, b, or c.
Problem
Approach
Steps
Complexity
Input: You are given four integers n, a, b, and c. You need to return the nth ugly number, where an ugly number is divisible by a, b, or c.
Example: Input: n = 3, a = 2, b = 3, c = 5
Constraints:
• 1 <= n, a, b, c <= 10^9
• 1 <= a * b * c <= 10^18
• It is guaranteed that the result will be in range [1, 2 * 10^9].
Output: Return the nth ugly number from the sequence.
Example: Output: 4
Constraints:
Goal: The goal is to find the nth ugly number in the sequence formed by numbers divisible by a, b, or c.
Steps:
• Perform a binary search to find the nth ugly number.
• At each step, calculate the number of ugly numbers less than or equal to the mid-point of the search range.
• Adjust the range based on the count of ugly numbers found and repeat until the correct ugly number is found.
Goal: The constraints ensure the result will be in the specified range. The values of a, b, c, and n are large but manageable for the solution approach used.
Steps:
• 1 <= n, a, b, c <= 10^9
• 1 <= a * b * c <= 10^18
• It is guaranteed that the result will be in range [1, 2 * 10^9].
Assumptions:
• It is assumed that the integers a, b, and c are not equal to zero.
• The given values are large but within the range allowed by the solution approach.
Input: Input: n = 3, a = 2, b = 3, c = 5
Explanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10, 12... The 3rd ugly number is 4.

Input: Input: n = 4, a = 2, b = 3, c = 4
Explanation: The ugly numbers are 2, 3, 4, 6, 8, 9, 10... The 4th ugly number is 6.

Input: Input: n = 5, a = 2, b = 11, c = 13
Explanation: The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th ugly number is 10.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus