Bird
Raised Fist0
Interview Prepmath-geometrymediumAmazonGoogleFacebook

Ugly Number II (Smooth Numbers)

Choose your preparation mode4 modes available
📋
Problem

Imagine you want to generate numbers whose only prime factors are 2, 3, or 5 - these 'smooth' numbers appear in computer graphics and signal processing.

Given an integer n, return the nth ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, and 5. The sequence starts with 1 as the first ugly number.

1 ≤ n ≤ 10^5
Edge cases: n = 1 → output 1 (smallest ugly number)n = 2 → output 2 (first prime factor multiple)n = 100 → output 1536 (larger input to test efficiency)
</>
IDE
def nthUglyNumber(n: int) -> int:public int nthUglyNumber(int n)int nthUglyNumber(int n)function nthUglyNumber(n)
def nthUglyNumber(n):
    # Write your solution here
    pass
class Solution {
    public int nthUglyNumber(int n) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int nthUglyNumber(int n) {
    // Write your solution here
    return 0;
}
function nthUglyNumber(n) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: 10Greedy approach picking next multiple of only one prime factor instead of merging all three.✅ Use min(dp[p2]*2, dp[p3]*3, dp[p5]*5) to select next ugly number and increment all pointers that match.
Wrong: 16Off-by-one error causing incorrect indexing or counting of ugly numbers.✅ Adjust loop and array indices to start counting from 1 and ensure correct increments.
Wrong: 0Missing base case handling for n=1, returning default or zero instead of 1.✅ Return 1 immediately if n == 1 before any computation.
Wrong: TLE or no outputUsing brute force checking each number for ugliness, causing exponential time complexity.✅ Implement O(n) DP with three pointers to generate ugly numbers efficiently.
Wrong: Incorrect number for n=14 (e.g., 18 instead of 20)Confusing 0/1 knapsack style restriction, disallowing repeated prime factor multiples.✅ Allow unlimited multiples of 2, 3, and 5 by merging pointers correctly.
✓
Test Cases
t1_01basic
Input{"n":10}
Expected12

The first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12. The 10th is 12.

t1_02basic
Input{"n":15}
Expected24

The 15th ugly number is 24; sequence includes 1,2,3,4,5,6,8,9,10,12,15,16,18,20,24.

t2_01edge
Input{"n":1}
Expected1

The smallest ugly number is 1 by definition.

t2_02edge
Input{"n":2}
Expected2

The second ugly number is 2, the first prime factor multiple after 1.

t2_03edge
Input{"n":100}
Expected1536

The 100th ugly number is 1536, testing correctness and efficiency on larger input.

t3_01corner
Input{"n":11}
Expected15

The 11th ugly number is 15, testing for greedy approach trap.

t3_02corner
Input{"n":14}
Expected20

The 14th ugly number is 20, testing confusion between 0/1 knapsack and unbounded multiples.

t3_03corner
Input{"n":7}
Expected8

The 7th ugly number is 8, testing off-by-one errors in indexing or counting.

t4_01performance
Input{"n":100000}
⏱ Performance - must finish in 2000ms

Test performance for n=100000; O(n) DP with three pointers must complete within 2 seconds.

Practice

(1/5)
1. Given the following code snippet, what is the output of clock.angleClock(3, 30)?
class ClockAngle:
    def __init__(self):
        self.precomputed = [[0]*60 for _ in range(12)]
        for h in range(12):
            for m in range(60):
                hour_angle = h * 30 + m * 0.5
                minute_angle = m * 6
                diff = abs(hour_angle - minute_angle)
                self.precomputed[h][m] = min(diff, 360 - diff)

    def angleClock(self, hour: int, minutes: int) -> float:
        return self.precomputed[hour % 12][minutes]

clock = ClockAngle()
print(clock.angleClock(3, 30))
easy
A. 105
B. 90
C. 75
D. 60

Solution

  1. Step 1: Calculate hour hand angle at 3:30

    Hour angle = 3 * 30 + 30 * 0.5 = 90 + 15 = 105 degrees.
  2. Step 2: Calculate minute hand angle and difference

    Minute angle = 30 * 6 = 180 degrees. Difference = |105 - 180| = 75 degrees. Minimal angle = 75 degrees.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Precomputed table stores minimal angle correctly -> 75 [OK]
Hint: Hour hand moves 0.5° per minute, not fixed 30° per hour [OK]
Common Mistakes:
  • Using only hour * 30 without minute adjustment
  • Returning absolute difference without min(., 360 - .)
2. Consider the following Python code snippet implementing the optimal approach for Max Points on a Line:
from collections import defaultdict
import math

def maxPoints(points):
    n = len(points)
    if n <= 2:
        return n
    max_points = 1
    points.sort()
    for i in range(n):
        if max_points >= n - i or max_points > n // 2:
            break
        slopes = defaultdict(int)
        duplicates = 0
        for j in range(i + 1, n):
            dx = points[j][0] - points[i][0]
            dy = points[j][1] - points[i][1]
            if dx == 0 and dy == 0:
                duplicates += 1
                continue
            gcd = math.gcd(dy, dx)
            if gcd != 0:
                dy //= gcd
                dx //= gcd
            if dx < 0:
                dx = -dx
                dy = -dy
            slopes[(dy, dx)] += 1
        curr_max = max(slopes.values(), default=0) + duplicates + 1
        max_points = max(max_points, curr_max)
    return max_points

points = [(1,1), (2,2), (3,3)]
print(maxPoints(points))
What is the output of this code?
easy
A. 2
B. 3
C. 1
D. 0

Solution

  1. Step 1: Trace outer loop with i=0

    Points sorted: [(1,1), (2,2), (3,3)]. For i=0, slopes computed with points (2,2) and (3,3) both have slope (1,1) after normalization.
  2. Step 2: Calculate max points for i=0

    Slopes[(1,1)] = 2, duplicates=0, so curr_max = 2 + 0 + 1 = 3. max_points updated to 3. Early termination triggers next iterations skipped.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    All points lie on the same line y=x, so output is 3 [OK]
Hint: All points on line -> max points equals total points [OK]
Common Mistakes:
  • Off-by-one in counting duplicates or base point
  • Ignoring early termination condition
3. What is the time complexity of the optimal approach that uses a hash set and checks pairs of points as diagonals to find the minimum area rectangle, given n points?
medium
A. O(n^4) because all quadruples of points are checked
B. O(n^2) because all pairs of points are checked and hash set lookups are O(1)
C. O(n^3) because for each pair, a linear search is done for complementary points
D. O(n log n) because points are sorted and then pairs are checked

Solution

  1. Step 1: Identify loops in the optimal approach

    The code iterates over all pairs of points (i,j), which is O(n^2).
  2. Step 2: Analyze point existence checks

    Checking if complementary points exist uses a hash set with O(1) average lookup, so no extra multiplicative factor.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Double loop + O(1) lookup -> O(n^2) time [OK]
Hint: Pairs checked, hash lookups O(1) -> O(n^2) [OK]
Common Mistakes:
  • Confusing with brute force O(n^4)
  • Assuming linear search inside pairs causes O(n^3)
4. What is the time complexity of the optimal single-pass Roman to Integer conversion algorithm, and why might some candidates mistakenly think it is higher?
medium
A. O(n^2) because each character is compared with all others
B. O(n) because each character is processed once with constant-time operations
C. O(n log n) due to sorting or searching steps
D. O(n) but with O(n) auxiliary space for storing intermediate results

Solution

  1. Step 1: Identify the loops and operations

    The algorithm iterates over the input string once, performing constant-time comparisons and arithmetic per character.
  2. Step 2: Address common misconceptions

    Some candidates mistakenly think the complexity is O(n^2) by assuming nested loops or repeated lookups, but no nested iteration occurs; no sorting or extra data structures are used.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Actual complexity is O(n), but candidates often incorrectly assume O(n^2) [Trap]
Hint: Single loop with constant work per char -> O(n) [OK]
Common Mistakes:
  • Assuming nested loops
  • Confusing auxiliary space with time
  • Thinking sorting is involved
5. Suppose the problem is modified so that negative integers can also be palindromes if their absolute values are palindromes (e.g., -121 is considered palindrome). Which modification to the optimal algorithm correctly handles this variant?
hard
A. Take the absolute value of the input at the start and proceed with the half reversal algorithm.
B. Remove the negative number check and reverse the entire number instead of half.
C. Convert the number to string including the sign and check palindrome with two pointers.
D. Ignore the sign and compare digits from both ends using modulo and division without reversal.

Solution

  1. Step 1: Understand new requirement

    Negative numbers are palindrome if their absolute values are palindromes.
  2. Step 2: Modify algorithm accordingly

    Taking absolute value removes sign issue; then half reversal works unchanged.
  3. Step 3: Evaluate other options

    Removing negative check without abs causes errors; full reversal risks overflow; string conversion uses extra space; digit comparison without reversal is complex.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Absolute value preserves palindrome property and fits optimal approach [OK]
Hint: Use absolute value to handle sign, keep optimal logic [OK]
Common Mistakes:
  • Removing negative check without abs
  • Switching to full reversal causing overflow
  • Using string conversion losing O(1) space
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard