fork download
  1. /**
  2.  * PROBLEM STATEMENT
  3.  * In a social network, a person can invite friends of his/her friend.
  4.   John wants to invite and add new friends. Complete the program below so that it prints
  5.   the names of the persons to whom John can send a friend request.
  6.  
  7.  * Input Format: The first line contains the value of the N which represent the number of friends.
  8.   Next N lines contain the name of the friend F followed by the number of friends of F
  9.   and finally their names separated by space.
  10.  
  11.  * Boundary Conditions: 2 <= N <= 10
  12.  * Output Format: The names to which John can send a friend request.
  13.  
  14.  * Example Input/Output 1:
  15.  * Input:
  16. 3
  17. Mani 3 Ram Raj Guna
  18. Ram 2 Kumar Kishore
  19. Mughil 3 Praveen Naveen Ramesh
  20.  
  21.  * Output:Raj Guna Kumar Kishore Praveen Naveen Ramesh
  22.  *
  23.  * Explanation:Ram is not present in the output as Ram is already John's friend.
  24.  *
  25.  * Example Input/Output 2:
  26.  * Input:
  27. 4
  28. Arjun 3 Bhuvana Ramya Rajesh
  29. Naveen 2 Arjun Sangeetha
  30. Rajesh 3 Narmada Madan Suresh
  31. Suresh 2 Pawan Adhil
  32.  * Output:Bhuvana Ramya Sangeetha Narmada Madan Pawan Adhil
  33. **/
  34. import java.util.HashSet;
  35. import java.util.Scanner;
  36. import java.util.StringTokenizer;
  37.  
  38. class Ideone {
  39. public static void main(String[] args) {
  40. Scanner sc = new Scanner(System.in);
  41. int N = sc.nextInt(); // No of friends
  42. sc.nextLine();
  43. HashSet<String> hs = new HashSet<>(); // to store name of the John's friends
  44. String invitation = "";
  45. for(int i =0; i < N; i++)
  46. {
  47. String str = sc.nextLine();
  48. String friend = "";
  49. int j =0;
  50. while(str.charAt(j)!= ' ')
  51. {
  52. friend = friend + str.charAt(j++);
  53. hs.add(friend); // add the name before the number to HashSet
  54. }
  55. j= j+2;
  56. invitation=invitation+str.substring(j)+" "; // remove name of John's friend from the string and store back remaining string
  57. }
  58. int j =0;
  59. StringTokenizer st = new StringTokenizer(invitation); // divide string into tokens
  60. while(st.hasMoreTokens())
  61. {
  62. String str = st.nextToken();
  63. if(!hs.contains(str)) {
  64. /* check if token(string) is already in hashset ie if the person already friend with John or not
  65.   if he is not then print str
  66.   */
  67. System.out.print(str+" ");
  68. }
  69. }
  70. }
  71. }
  72.  
Success #stdin #stdout 0.14s 321280KB
stdin
3
Mani 3 Ram Raj Guna
Ram 2 Kumar Kishore
Mughil 3 Praveen Naveen Ramesh
stdout
Raj Guna Kumar Kishore Praveen Naveen Ramesh