Dude Your Time Complexity is N^2logN^2 try reducing it to O(N^2) !!
Instead of Taking B array of size 100000000 Take ‘Count’ array of size N+1 since MEX of the array can be [0, N] so each time u get a MEX, update the count of MEX
Now you have count of each number .i. e. how many times each number is MEX now you can just iterate on count array and find kth small MEX;