#1201

Ugly Number III

Medium
MathBinary SearchCombinatoricsNumber TheoryBinary SearchInclusion-Exclusion Principle
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log(2 * 10^9))
Space
O(1)
O(1)
💡

Intuition

Time O(log(2 * 10^9))Space O(1)

Instead of checking each number, we can use binary search to efficiently find the nth ugly number by counting how many ugly numbers exist up to a certain point using the inclusion-exclusion principle.

⚙️

Algorithm

3 steps
  1. 1Step 1: Define a function f(k) that counts how many ugly numbers are ≤ k using the inclusion-exclusion principle.
  2. 2Step 2: Use binary search between 1 and a large enough number (2 * 10^9) to find the smallest number x such that f(x) = n.
  3. 3Step 3: Return x as the nth ugly number.
solution.py23 lines
1# Full working Python code
2
3from math import gcd
4
5def lcm(x, y):
6    return x * y // gcd(x, y)
7
8def countUglyNumbers(k, a, b, c):
9    ab = lcm(a, b)
10    ac = lcm(a, c)
11    bc = lcm(b, c)
12    abc = lcm(ab, c)
13    return (k // a) + (k // b) + (k // c) - (k // ab) - (k // ac) - (k // bc) + (k // abc)
14
15def nthUglyNumber(n, a, b, c):
16    left, right = 1, 2 * 10**9
17    while left < right:
18        mid = (left + right) // 2
19        if countUglyNumbers(mid, a, b, c) < n:
20            left = mid + 1
21        else:
22            right = mid
23    return left

Complexity note: The time complexity is O(log(2 * 10^9)) due to the binary search, and the space complexity is O(1) since we only use a few variables.

  • 1Understanding the inclusion-exclusion principle is crucial for counting ugly numbers efficiently.
  • 2Binary search allows us to quickly hone in on the nth ugly number without generating all previous numbers.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.