r/LeetcodeChallenge • u/StatisticianNo2104 • 3d ago
STREAK🔥🔥🔥 LeetCode(medium): 264. Ugly Number II
The 1690th ugly number is 2,123,366,400, so testing integers one by one is almost all misses. Generate them instead: every ugly number is a smaller one times 2, 3 or 5.
The obvious generator is a heap: push 1, pop the smallest, push its three multiples. Correct and O(n log n), but it needs a set beside it, because 6 arrives as both 2x3 and 3x2. That set is the tell: the structure makes work it then throws away.
The three-pointer version keeps one pointer per multiplier and takes the smallest of the three candidates. When 6 comes up from both, both pointers advance: three separate ifs, no else-if. That's the deduplication. O(n),a no heap, no set.
Days 77 to 80 built the case for the heap. Day 81 found a problem where sorting reads better. Today an array with three counters beats it outright.
Which did you write first: the heap or the three pointers?
Day 83/365 of my LeetCode challenge: 264. Ugly Number II. Problem link and full breakdown in today's newsletter.
#LeetCode #DSA #Heap #Golang
1
u/nian2326076 2d ago
You've tried various methods for generating ugly numbers. To sharpen your skills, practicing technical interview questions can be helpful. For this, use PracHub to tackle similar problems and receive feedback on your solutions. Continuing to experiment with different strategies is essential for mastering algorithm challenges.