Ugly Number II

MediumDynamic Programming1d dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Call a positive integer **ugly** if its only prime factors are 2, 3 and 5. By convention 1 is ugly (it has no prime factors), so the ugly numbers in increasing order begin 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, .... Given n, return the n-th ugly number, counting from 1 (so n = 1 returns 1). Aim for O(n) time: generate the ugly numbers in order instead of testing every integer.

Examples

Input: n = 10
Output: 12
The first ten ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12.
Input: n = 1
Output: 1
1 is the first ugly number by definition.

Constraints

  • 1 <= n <= 1690
  • The answer fits in a 32-bit signed integer

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More 1d dp problems