Ugly Number II
Problem Statement
An ugly number is a positive integer whose only prime factors are 2, 3 and 5. The number 1 counts as ugly.
Given n, return the n-th ugly number when the ugly numbers are listed in increasing order.
n: a positive integer.
The n-th ugly number, as an int.
The first ten ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12.
The first ugly number is 1.
- β’ 1 β€ n β€ 1690
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Check each integer for factors other than 2, 3 and 5 until n ugly numbers are found
Pop the smallest candidate n times; push its Γ 2, Γ 3 and Γ 5 unless already seen
The next ugly number is the smallest of three next products; move every pointer that produced it
Count upward from 1. A number is ugly if dividing out every 2, 3 and 5 leaves 1. Keep counting ugly numbers until there are n of them.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like K-way Merge translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.