Skip to content

Commit 4356091

Browse files
my solution for 1823
1 parent 1fadd63 commit 4356091

File tree

1 file changed

+38
-3
lines changed

1 file changed

+38
-3
lines changed

problems/1823/jeremymanning.md

+38-3
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,46 @@
11
# [Problem 1823: Find the Winner of the Circular Game](https://leetcode.com/problems/find-the-winner-of-the-circular-game/description/?envType=daily-question)
22

33
## 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+
521
## 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
624

725
## Attempted solution(s)
826
```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]
1136
```
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+
![Screenshot 2024-07-07 at 11 30 13 PM](https://github.com/ContextLab/leetcode-solutions/assets/9030494/ff26e9c1-db59-49d9-8d94-021804e5c53d)
45+
46+
Slow and inefficient...but solved!

0 commit comments

Comments
 (0)