#263

Ugly Number

Easy
MathMathGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

Instead of checking all numbers up to n, we can directly divide by the allowed prime factors until we either reach 1 or a number that cannot be further divided.

⚙️

Algorithm

5 steps
  1. 1Step 1: If n is less than or equal to 0, return false.
  2. 2Step 2: While n is divisible by 2, divide n by 2.
  3. 3Step 3: While n is divisible by 3, divide n by 3.
  4. 4Step 4: While n is divisible by 5, divide n by 5.
  5. 5Step 5: Return n equals 1.
solution.py7 lines
1def isUgly(n):
2    if n <= 0:
3        return False
4    for prime in [2, 3, 5]:
5        while n % prime == 0:
6            n //= prime
7    return n == 1

Complexity note: The time complexity is O(log n) because we are dividing n by 2, 3, or 5, which reduces n significantly each time.

  • 1An ugly number can only have 2, 3, and 5 as its prime factors.
  • 2The number 1 is considered an ugly number since it has no prime factors.

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