Why do i get a "terminated due to timeout" error for my code at hackerrank?
The problem with your logic is that it is implemented using ArrayList
which is a sequential structure. Any search in List will be sequential and for large test cases its taking too much time to lookup in your names list.
Hash map is more appropriate for a phone book example as it keeps data in key, value pair and look ups are fast because of hashing
Here is a version that is implemented using HashMap
Map<String,Integer> phonebook = new HashMap<>();
Scanner in = new Scanner(System.in);
int n=in.nextInt();
in.nextLine();
for(int i=0;i<n;i++)
{
String name=in.nextLine();
int phone=in.nextInt();
in.nextLine();
phonebook.put(name,phone);
}
while(in.hasNext())
{
String s=in.nextLine();
Integer phone = phonebook.get(s);
if(phone==null){
System.out.println("Not found");
} else {
System.out.println(s+"="+phone);
}
}
Hope this explains.
Usually "Terminated due to timeout error" occurs when your code takes longer time to execute than the maximum time set by the Problem Setters(Hackerrank).
The problem you tried is intended to teach you how HashMaps are used, but you solved the problem using arrays. Searching in arrays takes O(n)longer time than that of Maps which are generally hashed to search in O(1) time. For smaller input your program works fine, but for larger inputs like 100000 entries, It will take longer time and result in time out. So Use Maps instead of Arrays and ArrayLists