I am doing some interview prep and working on this leetcode question I came across. The questions states Given two integers m and n, loop repeatedly through an array of m and remove each nth element. Return the last element left. (If m = 7 and n = 4, then begin with the array 1 2 3 4 5 6 7 and remove, in order, 4 1 6 5 2 7 and return 3.)
. From my work it looks like 7 will be the last number not 3.
My thought process was to add all the elements in a ArrayList
or LinkedList
and then use the remove()
function to get rid of the position thats passed. What I would like to know is how can I start from the element I remove and just add that many indexes and remove the next number? I have my code down below.
static int arraryReturn (int [] a, int b, int c) {
LinkedList<Integer> myList = new LinkedList<>();
for(int i =0; i< a.length;i++) {
myList.add(i);
}
while(myList.size() > 0) {
myList.remove(c);
}
return -1;
}