The input is:
An int[][]
, each sub array contains 2 int as {parent, child}, means there is a path from parent
-> child
.
e.g
{ { 1, 3 }, { 2, 3 }, { 3, 6 }, { 5, 6 }, { 5, 7 }, { 4, 5 }, { 4, 8 }, { 8, 9 } };
Or as a tree structure:
1 2 4 \ / / \ 3 5 8 \ / \ \ 6 7 9
The task is:
Giving 2 value (x, y), return a boolean value, to indicate whether they have any common parent(s).
Sample input and output:
[3, 8] => false [5, 8] => true [6, 8] => true
My idea:
- Represent the input data as a DAG graph, in which data are stored in a Map like this
Map<Integer, LinkedList<Integer>>
, where key is the vertex, value is its adjacency list. And the direction in graph is reversed (compared to input data) aschild -> parent
, so that easy to search for parent. - Use a function
findAvailableParents(Integer vertex)
to find all parents (direct and indirect) for a single vertex, and returnSet<Integer>
. - Thus, only need to call
findAvailableParents()
once for each input vertex, then compare whether the 2 returnedSet
s have any intersection. If yes, then they have common parent; otherwise, they don't.
My questions are:
- The time complexity in the solution above is between O(1) ~ O(E), right? (E is edge counts in the graph)
- Is there a better solution?