Back to photostream

Find the Winner of the Circular Game LeetCode Solution

Problem Statement

Find the Winner of the Circular Game LeetCode Solution - There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 we eliminate the kth person or person with (k - 1)th index, in this case being 2(index 1). Now we have 3 people remaining 1,3,4 with starting person as 3 (index 2) or person with (k + 1)th index for the next elimination, and we know that for 3 people, the winner will be the person at the 2nd index beginning with 3 as the starting point i.e. 1(index 0) or ((k + 1) + f(n - 1)) % n, where (k +1) is starting index and f(n - 1) is the answer for (n - 1) persons.

Code

Java Program of Find the Winner of the Circular Game:

class Solution {

public int findTheWinner(int n, int k) {

return findWinnerHelper(n, k - 1) + 1;

}

 

private int findWinnerHelper(int n, int k) {

if (n == 1) {

return 0;

}

 

return ((k + 1) % n + findWinnerHelper(n - 1, k)) % n;

}

}

C++ Program of Find the Winner of the Circular Game:

class Solution

{

public:

int findTheWinner(int n, int k)

{

return findWinnerHelper(n, k - 1) + 1;

}

private:

int findWinnerHelper(int n, int k)

{

if (n == 1)

{

return 0;

}

return ((k + 1) % n + findWinnerHelper(n

 

www.tutorialcup.com/leetcode-solutions/find-the-winner-of...

68 views
0 faves
0 comments
Uploaded on July 12, 2022