People who know story by time stamp -code

People who know story by time stamp is to simulate social network using graph data structure. The individual person is a node. The edge is from one person to another person when one tells another a story. The edge is bi-directional since both people know the story.

The graph can be represented as adjacent list. HashMap is used, in which the keys are all people who tell or be told the story. The value is the edge from the person (in key) to its neighbors. The value also contains a value of timestamp which marks when the story is told. The timestamp can be seen as “weight” in a weighted graph. At the end, we should find out all people who know the story by certain timestamp. The question can be solved with depth first search and memoization.

graph dfs

In this question, the timestamp associated with the neighbor node should be the driven factor. We have to compare the timestamp along the traversal path. Some people may not know the story if time sequence is not right. The initial timestamp value is 0.

The timestamp is transferred as a parameter in the DFS utility method. It should be compared with all the adjacent nodes’ timestamp. If the input time is smaller than the neighbor’s timestamp, that means these two people have the opportunity to tell the story when they meet. We add this adjacent node as the output group who know the story. Otherwise, he is excluded. At the end, we can find all people who know the story.

Google Interview Question (CareerCup):
When a person who knows it meets any other person, they immediately share the story with them. Initially, only person 1 knows the story. Given a list of meetings between people in a form of (person_1_id, person_2_id, timestamp) construct a list of the persons who will know the story at the very end.

Example: [(1, 2, 100), (3,4, 200), (1,3, 300), (2,5, 400)], 1 // The events could be out of order.
Person 2 will learn the story at the moment 100, person 3 — at the moment 300, person 5 — in the moment 400. Person 4 will never learn the story. So the answer is [1, 2, 3, 5].

Eg2: [(1, 2, 100), (2, 3, 100), (4, 5, 100)], 2
where the first parameter is array of the Persons meet at particular timestamp, second parameter is the PersonId who knows the story first.
Output: [1, 2, 3].





graph dfs doodle

1-[2 100, 3 300]
2-[1 100, 5 400]
3-[4 200, 1 300]
4-[3 200]
5-[2 400]
People who know story: [1, 2, 3, 5]
1-[2 100]
2-[1 100, 3 100]
3-[2 100]
4-[5 100]
5-[4 100]
People who know story: [1, 2, 3]

O Notation:
Time complexity: O(V+E)
Space complexity: O(V)
V is total number of people, E is number of connections

Download PeopleWhoKnowStoryByTimeStamp.js
Java Coding Interview Pocket Book (2nd Edition)
Weighted graph implementation

Comments are closed