Consider ‘arr’ = [(1, 2, 100), (3, 4, 200), (1, 3, 300), (2, 5, 400)]
Person 1 will tell the story to person 2 at 100th timeStamp.
Person 1 will tell the story to person 3 at 300th timeStamp.
Person 2 will tell the story to person 5 at 400th timeStamp.
Person 4 will not be able to learn the story.
So the output will be [1, 2, 3, 5].
The first line contains a single integer ‘T’ denoting the number of test cases, then each test case follows.
The first line of each test case contains an integer ‘N’, denoting the number of meeting between people.
The next ‘N’ lines contain 3 space-separated integers denoting ‘person1’, ‘person2’, and ‘timeStamp’.
Output Format :
For each test case, print an array of integers in sorted order representing all persons who will know the story by the end.
The output for each test case will be printed in a separate line.
Note :
You are not required to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= N <= 10^5
1 <= person1 <= person2 <= 10^6
1 <= timeStamp <= 10^9
Time limit: 1 sec
2
4
1 2 100
3 4 200
1 3 300
2 5 400
3
1 2 1
2 3 2
3 4 3
1 2 3 5
1 2 3 4
For test case 1 :
Person 1 will tell the story to person 2 at 100th timeStamp.
Person 1 will tell the story to person 3 at 300th timeStamp.
Person 2 will tell the story to person 5 at 400th timeStamp.
Person 4 will not be able to learn the story.
So the output will be [1, 2, 3, 5]
For test case 2 :
Person 1 will tell the story to person 2 at 1st timeStamp.
Person 2 will tell the story to person 3 at 2nd timeStamp.
Person 3 will tell the story to person 4 at 3rd timeStamp.
So the output will be [1, 2, 3, 4]
2
2
2 3 1
1 2 2
3
1 4 2
3 5 1
4 2 3
1 2
1 2 4
Can you make directed connections between persons?
In the approach, we will use a depth-first search to find all persons who will know the store by the end. We will maintain a visited HashMap to store the people who have been visited. We will maintain a HashMap graph to create a directed edge for the meeting between the people.
We will create a recursive function helper(graph, visited, index, time) where graph and visited is the HashMap, the index is the current person, and time is the current time.
Algorithm:
O(N*log(N)), where ‘N’ is the number of meetings in the array.
We are using a depth-first search approach to traverse through all people, which takes O(N), and after that, we are sorting, which takes O(N*log(N)) time. Hence the overall complexity is O(N*log(N))
O(N), where ‘N’ is the number of meetings in the array.
In the worst case, we maintained a HashMap, holding most ‘N’ elements, and the recursion stack also takes O(N). So the space complexity is O(N+N) which is effectively O(N). Hence the overall space complexity is O(N).