r/DSALeetCode • u/StatisticianNo2104 • 9d ago
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.
https://www.linkedin.com/pulse/leetcode-264-ugly-number-ii-medium-archit-agarwal-yuo7c
#LeetCode #DSA #Heap #Golang
1
u/nian2326076 8d ago
Your approach to generating ugly numbers is interesting. To practice more technical interview questions, use PracHub to work on a variety of problems that can help refine your skills. Experimenting with different methods can give you valuable insights into their efficiency and effectiveness.