|
1 | 1 | # [Problem 1823: Find the Winner of the Circular Game](https://leetcode.com/problems/find-the-winner-of-the-circular-game/description/?envType=daily-question)
|
2 | 2 |
|
3 | 3 | ## Initial thoughts (stream-of-consciousness)
|
4 |
| - |
| 4 | +- The first solution that comes to mind is to just run out the "game" until there is only one friend remaining |
| 5 | +- It might be useful to copy the list to a circular linked list (so that the last element links back to the first). This would take $O(n)$ time (where $n$ is the number of friends in the circle), and the final algorithm will almost certainly have worse complexity, so it would be "cheap" to do this. |
| 6 | +- On the other hand, we could also just use `del` or `pop` to remove the relevant item with each round. We'd need to keep track of where in the list we are ($i$), and just subtract the current list length from $i$ whenever $i$ exceeds $n$. |
| 7 | +- I could potentially add a class to do this: |
| 8 | + - wraps `list` |
| 9 | + - adds an "index" to track where we are in the list |
| 10 | + - adds a function for incrementing the index (wrapping if needed) |
| 11 | + - adds a function for removing an element and updating the length accordingly |
| 12 | +- Or this could be done using a `set`: |
| 13 | + - start with `x = set(range(1, n + 1))` and `i = 0`...or actually, that won't work, since `set`s are unordered. |
| 14 | +- So let's say we start with `x = list(range(1, n + 1))` and `i = 0` |
| 15 | + - until `len(x) == 1`: |
| 16 | + - increment $i$ by $k - 1$ (the -1 is to account for counting the "current" friend) |
| 17 | + - wrap $i$ (i.e., `i %= len(x)`) |
| 18 | + - remove `x[i]` |
| 19 | + - Return the remaining friend |
| 20 | + |
5 | 21 | ## Refining the problem, round 2 thoughts
|
| 22 | +- If $k == 1$ then the "winner" has to just be $n$. If $k == 2$, the winner would be the second-to-last odd number. Maybe there's a pattern here...🤔 |
| 23 | +- Let's go with the "easy" solution first and then refine if needed |
6 | 24 |
|
7 | 25 | ## Attempted solution(s)
|
8 | 26 | ```python
|
9 |
| -class Solution: # paste your code here! |
10 |
| - ... |
| 27 | +class Solution: |
| 28 | + def findTheWinner(self, n: int, k: int) -> int: |
| 29 | + friends = list(range(1, n + 1)) |
| 30 | + i = 0 |
| 31 | + while len(friends) > 1: |
| 32 | + i = (i + k - 1) % len(friends) |
| 33 | + del friends[i] |
| 34 | + |
| 35 | + return friends[0] |
11 | 36 | ```
|
| 37 | +- given test cases pass |
| 38 | + - `n = 49, k = 6`: pass |
| 39 | + - `n = 100, k = 17`: pass |
| 40 | + - `n = 302, k = 302`: pass |
| 41 | + - `n = 2, k = 1`: pass |
| 42 | +- seems promising; submitting... |
| 43 | + |
| 44 | + |
| 45 | + |
| 46 | +Slow and inefficient...but solved! |
0 commit comments