An ugly number is a positive integer that is divisible by at least one of three given numbers: a, b, or c.

Given four integers n, a, b, and c, your task is to find the n-th ugly number in the sequence of all ugly numbers sorted in ascending order.

Example: If a = 2, b = 3, c = 5, then the ugly numbers are: 2, 3, 4, 5, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20...

The challenge is to find this efficiently for large values of n (up to 2 ร— 109), making a brute force approach impractical.

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 3, a = 2, b = 3, c = 5
โ€บ Output: 4
๐Ÿ’ก Note: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10, 12... The 3rd ugly number is 4.
example_2.py โ€” Larger Input
$ Input: n = 4, a = 2, b = 3, c = 4
โ€บ Output: 6
๐Ÿ’ก Note: Since 4 = 2ร—2, numbers divisible by 4 are also divisible by 2. The ugly numbers are 2, 3, 4, 6, 8, 9... The 4th ugly number is 6.
example_3.py โ€” Edge Case
$ Input: n = 1000000000, a = 2, b = 217983653, c = 336916467
โ€บ Output: 1999999984
๐Ÿ’ก Note: This demonstrates why we need an efficient algorithm - brute force would be impossible for such large n.

Visualization

Tap to expand
Binary Search + Inclusion-Exclusion VisualizationMultiples of aMultiples of bMultiples of clcm(a,b,c)Inclusion-Exclusion Formula:Count(x) = |A| + |B| + |C| - |AโˆฉB| - |AโˆฉC| - |BโˆฉC| + |AโˆฉBโˆฉC|Binary Search Range: [1, n ร— min(a,b,c)]O(log n) iterationsO(1) counting per iterationTotal: O(log n)
Understanding the Visualization
1
Binary Search Setup
Search space is from 1 to n ร— min(a,b,c) since the n-th ugly number can't exceed this
2
Counting Function
For any value x, count ugly numbers โ‰ค x using inclusion-exclusion principle
3
Include Individual Sets
Add โŒŠx/aโŒ‹ + โŒŠx/bโŒ‹ + โŒŠx/cโŒ‹ to count multiples of each
4
Exclude Intersections
Subtract โŒŠx/lcm(a,b)โŒ‹ + โŒŠx/lcm(a,c)โŒ‹ + โŒŠx/lcm(b,c)โŒ‹ to avoid double counting
5
Include Triple Intersection
Add back โŒŠx/lcm(a,b,c)โŒ‹ for numbers divisible by all three
Key Takeaway
๐ŸŽฏ Key Insight: Instead of generating ugly numbers sequentially (slow), we binary search on the answer and use inclusion-exclusion principle to count ugly numbers โ‰ค any value in constant time, achieving O(log n) complexity.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n ร— result)

We potentially check every number up to the n-th ugly number, which could be very large

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a few variables to track count and current number

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค n โ‰ค 2 ร— 109
  • 2 โ‰ค a, b, c โ‰ค 109
  • Important: The result will fit in a 32-bit signed integer
Asked in
Google 45 Microsoft 35 Amazon 30 Meta 25
34.5K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen