I am trying to solve a programming problem on a coding platform. When I execute it on my PC, it works perfectly, but when I submit the code on the coding platform, it throws a "Time Limit Exceeded" error. Can someone check my solution and help optimize it?
In a social network, a person can invite friends of his/her friend. John wants to invite and add new friends. Complete the program below so that it prints the names of the persons to whom John can send a friend request.
Input format:
The first line contains the value of the N which represent the number of friends. N lines contain the name of the friend F followed by the number of friends of F finally their names separated by space.
Input:
3 Mani 3 Ram Raj Guna Ram 2 Kumar Kishore Mughil 3 Praveen Naveen RameshOutput:
Raj Guna Kumar Kishore Praveen Naveen RameshExplanation:
Ram is not present in the output as Ram is already John's friend.
My Approach
- Extract the first word of each line and store them in
HashSetand remove them from the string. Names stored inHashSetare already friends of the person (John). - Now extract the names from the String using
StringTokenizerand check whether the name is contained in theHashSet. If it is not present then print it.
And can we solve this problem using graph/trees. The problem statement and my code can be found here.
import java.util.HashSet;
import java.util.Scanner;
import java.util.StringTokenizer;
class Ideone {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt(); // No of friends
sc.nextLine();
HashSet<String> hs = new HashSet<>(); // to store name of the John's friends
String invitation = "";
for(int i =0; i < N; i++)
{
String str = sc.nextLine();
String friend = "";
int j =0;
while(str.charAt(j)!= ' ')
{
friend = friend + str.charAt(j++);
hs.add(friend); // add the name before the number to HashSet
}
j= j+2;
invitation=invitation+str.substring(j)+" "; // remove name of John's friend from the string and store back remaining string
}
int j =0;
StringTokenizer st = new StringTokenizer(invitation); // divide string into tokens
while(st.hasMoreTokens())
{
String str = st.nextToken();
if(!hs.contains(str)) {
/* check if token(string) is already in hashset ie if the person already friend with John or not
if he is not then print str
*/
System.out.print(str+" ");
}
}
}
}