Time Limit failed

import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while(t>0){
int n = scan.nextInt();
int res = nextPrime(n);
System.out.println(res);
t–;
}

}
public static int nextPrime(int n){
	ArrayList<Integer> list = new ArrayList<>();
	list.add(2);
	int i = 3;
	int idx = 1;
	while(idx<n){
		boolean flag = true;
		for(int val : list){
			if(i%val==0){
				flag = false;
			}
			
		}
		if(flag){
			list.add(i);
			idx++;	
			}
		i++;
	}
	return list.get(n-1);
	} 
}

Hi vaibhav,
If you clearly observe the constraints the Test Cases are 10,000 in worst case.
Your code is currently having time complexity of O(Tnp),in worst case
where T =Test cases, n= nth Number and p=no. of primes found till n.
Now consider the worst case as:
T=10,000
n=10,000
As there are nearly 1229 prime numbers between 1 to 10,000 therefore p=1,000(taking approx val).
So the complexity comes out to be (10^4)(10^4)(10^3)=10^12 .
But upto 10^8 Operations per second are acceptable.
Hence,Use an efficient method of generating Primes


Revert back here with Optimised Code.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.