Skip to content

Commit 580e6c1

Browse files
My solution to 264
1 parent 0d0916b commit 580e6c1

File tree

1 file changed

+46
-2
lines changed

1 file changed

+46
-2
lines changed

problems/264/jeremymanning.md

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,55 @@
11
# [Problem 264: Ugly Number II](https://leetcode.com/problems/ugly-number-ii/description/?envType=daily-question)
22

33
## Initial thoughts (stream-of-consciousness)
4+
- One way to solve this would be:
5+
- Start the sequence with 1
6+
- Each subsequent element is generated by multiplying a previous element by 2, 3, or 5
7+
- We could have 3 indices/pointers to keep track of the next thing to multiply by 2/3/5 (initially these should all point to the first element, which is 1). Let's call these `i2`, `i3`, and `i5`.
8+
- Now we just:
9+
- Take the current 2/3/5 pointers' numbers and multiply by 2/3/5
10+
- Take the minimum of the results (this occurs for pointer `i`). Note: it's possible that *multiple* pointers could match-- e.g., if `i2 == 3` and `i3 == 2` then both the `i2` and `i3` results will be 6.
11+
- Add it to the list and increment the matching pointer(s) (by 1).
12+
- Repeat until we've gotten `n` numbers in the sequence and then return the last number in the sequence
413

514
## Refining the problem, round 2 thoughts
15+
- Let's see if this works...
616

717
## Attempted solution(s)
818
```python
9-
class Solution: # paste your code here!
10-
...
19+
class Solution:
20+
def nthUglyNumber(self, n: int) -> int:
21+
ugly_numbers = [0] * n
22+
ugly_numbers[0] = 1
23+
24+
i2, i3, i5 = 0, 0, 0
25+
next2, next3, next5 = 2, 3, 5
26+
27+
for i in range(1, n):
28+
x = min(next2, next3, next5)
29+
ugly_numbers[i] = x
30+
31+
if x == next2:
32+
i2 += 1
33+
next2 = ugly_numbers[i2] * 2
34+
35+
if x == next3:
36+
i3 += 1
37+
next3 = ugly_numbers[i3] * 3
38+
39+
if x == next5:
40+
i5 += 1
41+
next5 = ugly_numbers[i5] * 5
42+
43+
return ugly_numbers[n - 1]
1144
```
45+
- Given text cases pass
46+
- Let's try some others:
47+
- `n = 1690`: pass
48+
- `n = 250`: pass
49+
- Ok, it's probably good; submitting...
50+
51+
![Screenshot 2024-08-17 at 11 39 32 PM](https://github.com/user-attachments/assets/a221898c-7840-4834-a190-41047867352b)
52+
53+
Woah, apparently this was the way to solve it!
54+
55+

0 commit comments

Comments
 (0)