Skip to content

264. Ugly Number II #341

Answered by topugit
mah-shamim asked this question in Q&A
Aug 18, 2024 · 1 comments · 1 reply
Discussion options

You must be logged in to vote

We can use a dynamic programming approach. We'll maintain an array to store the ugly numbers and use three pointers to multiply by 2, 3, and 5.

Let's implement this solution in PHP: 264. Ugly Number II

<?php
function nthUglyNumber($n) {
    $uglyNumbers = array_fill(0, $n, 0);
    $uglyNumbers[0] = 1;
    
    $i2 = $i3 = $i5 = 0;
    $next2 = 2;
    $next3 = 3;
    $next5 = 5;

    for ($i = 1; $i < $n; $i++) {
        $nextUgly = min($next2, $next3, $next5);
        $uglyNumbers[$i] = $nextUgly;

        if ($nextUgly == $next2) {
            $i2++;
            $next2 = $uglyNumbers[$i2] * 2;
        }
        if ($nextUgly == $next3) {
            $i3++;
            $next3 = $uglyNumbers[

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@mah-shamim
Comment options

mah-shamim Aug 18, 2024
Maintainer Author

Answer selected by mah-shamim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants