import java.util.*;
public class Solution {
    public int LastRemaining_Solution(int n, int m) {
        Queue<Integer> que = new LinkedList<Integer>();
        for(int i = 0; i < n; i++){
            que.offer(i);
        }
        int count = 0;
        while(que.size() != 1){
            if(count != m - 1){
                que.offer(que.poll());
                count++;
            }else {
                que.poll();
                count = 0;
            }
        }
        return que.peek();

    }
}