Skip to content

Commit 833211a

Browse files
Commit code and explanation
1 parent 9540b5e commit 833211a

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
Intuition
2+
Consider the Math problem with ref in wiki
3+
Josephus problem
4+
5+
This problem can be solved with simulation, but it is basically a Math problem. It needs to study for a while.
6+
7+
A simulation C++ using queue is also presented.
8+
9+
Approach
10+
Let f(n,k) denote the position of the survivor.
11+
The wiki says:
12+
13+
The position of the survivor in the remaining circle would be f(n−1,k) if counting is started at 1; shifting this to account for the fact that the starting point is (kmodn)+1 yields the recurrence f(n,k)=((f(n−1,k)+k−1)modn)+1, with f(1,k)=1
14+
15+
Use it & done.
16+
17+
I would not say such problems would be easy. The hardest part is to find out & to prove the recurrence. Even LC has just only explained for k=2.
18+
19+
An iterative based on the recurrence is also provided.
20+
21+
Theorem for general Josephus problem
22+
Let j(n,k,i) denote the ith number should be removed. Then the following recurrence holds
23+
j(n,k,i+1)≡(k+j(n−1,k,i))(modn)
24+
where the initial value j(n,k,1)=(k−1)(modn)
25+
26+
Note f(n,k)=j(n,k,n) in Theorem
27+
28+
29+
30+
is used, when j(n,k,i+1)≡0 then j(n,k,i+1)=n.
31+
32+
Complexity
33+
Time complexity:
34+
O(n)
35+
36+
Space complexity:
37+
O(n)
38+
iterative Version: O(1)

190-8th_July-Find_winner/code.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution
2+
{
3+
public:
4+
static int findTheWinner(int n, int k)
5+
{
6+
if (n == 1)
7+
return 1;
8+
return (findTheWinner(n - 1, k) + (k - 1)) % n + 1;
9+
}
10+
};
11+
12+
auto init = []()
13+
{
14+
ios::sync_with_stdio(0);
15+
cin.tie(0);
16+
cout.tie(0);
17+
return 'c';
18+
}();

0 commit comments

Comments
 (0)