Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Ugly Number

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "263" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

An ugly number is a positive integer which does not have a prime factor other than 2, 3, and 5. Given an integer n, return true if n is an ugly number. Example 1: Input: n = 6 Output: true Explanation: 6 = 2 × 3 Example 2: Input: n = 1 Output: true Explanation: 1 has no prime factors. Example 3: Input: n = 14 Output: false Explanation: 14 is not ugly since it includes the prime factor 7. Constraints: -231 <= n <= 231 - 1

Explanation

  • Iterative Division: Repeatedly divide the given number n by 2, 3, and 5 until it's no longer divisible by any of these numbers.
    • Final Check: After the divisions, if the remaining number is 1, it means the original number only had 2, 3, and 5 as prime factors, hence it's an ugly number. Otherwise, it's not.
  • Time Complexity: O(log n), where n is the input number. Space Complexity: O(1).

Code

    def is_ugly(n: int) -> bool:
    """
    An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
    Given an integer n, return true if n is an ugly number.

    For example:
    is_ugly(6) == True
    is_ugly(1) == True
    is_ugly(14) == False
    """
    if n <= 0:
        return False

    for factor in [2, 3, 5]:
        while n % factor == 0:
            n //= factor

    return n == 1

More from this blog

C

Chatmagic blog

2894 posts