Problem Statement - https://practice.geeksforgeeks.org/problems/game-of-death-in-a-circle1840/1
class Solution {
static int safePos(int n, int k) {
// code here
ArrayList<Integer> list = new ArrayList<>();
for(int i=0; i<n; i++) {
list.add(i+1);
}
// As we are dealing with 0 indexed base arraylist
return helper(list, k-1, 0);
}
static int helper(ArrayList<Integer> list, int k, int curr) {
// As soon as the size of the list becomes 1, return that number
if(list.size()==1)
{
return list.get(0);
}
// get the next index for which element should be removed
int index = (curr+k)%(list.size());
// remove the element
list.remove(index);
// recursively call the helper method on the smaller input
return helper(list, k, index);
}
};
Time complexity - O(n)