Solving Leetcode Interviews in Seconds with AI: Ugly Number II
Introduction
In this blog post, we will explore how to solve the LeetCode problem "264" 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 whose prime factors are limited to 2, 3, and 5. Given an integer n, return the nth ugly number. Example 1: Input: n = 10 Output: 12 Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers. Example 2: Input: n = 1 Output: 1 Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. Constraints: 1 <= n <= 1690
Explanation
Here's an efficient solution to find the nth ugly number:
- Dynamic Programming: Build an array of ugly numbers in increasing order. Each ugly number is a multiple of 2, 3, or 5 from a previous ugly number.
- Pointers: Maintain three pointers, one for each of the prime factors 2, 3, and 5. These pointers indicate the index of the smallest ugly number to multiply with each prime factor.
Min Heap Alternative (Less Efficient): While a min-heap could work, the dynamic programming approach is generally faster due to less overhead.
Time & Space Complexity: O(n) time, O(n) space
Code
def nthUglyNumber(n: int) -> int:
"""
Finds the nth ugly number.
Args:
n: The index of the ugly number to find (1-indexed).
Returns:
The nth ugly number.
"""
if n <= 0:
return 0
ugly_numbers = [1] * n
p2 = p3 = p5 = 0
for i in range(1, n):
ugly_numbers[i] = min(ugly_numbers[p2] * 2, ugly_numbers[p3] * 3, ugly_numbers[p5] * 5)
if ugly_numbers[i] == ugly_numbers[p2] * 2:
p2 += 1
if ugly_numbers[i] == ugly_numbers[p3] * 3:
p3 += 1
if ugly_numbers[i] == ugly_numbers[p5] * 5:
p5 += 1
return ugly_numbers[n - 1]