-1

I'm trying to figure out how to compare n number of lists to find the common link among the lists. For example following are the lists:

A = [1,2,3],
B = [3,4,5,6],
C = [6,7,8],
D = [4,5,6],
      ..
      ..

The input to this program will be A and C (looking for a way to find a common link between A & C)

The expected output is 
C-->B-->A (A & C are linked through B)

The challenge might be find deeper level of connections e.g.

A = [1,2,3],
B = [3,4,5,6],
C = [6,7,8],
D = [8,9,10],
E = [10,11,12]      ..
      ..

The input to this program will be A and E (looking for a way to find a common link between A & E)

The expected output is 
E-->D-->C-->B-->A (A & E are linked through D,C,B)

I've looked at this solution that compares two lists but it is solving a very different problem: How to find common elements in list of lists?

Community
  • 1
  • 1
Listy
  • 1
  • 2
  • What is your programming language? – 4castle Mar 21 '16 at 17:17
  • can you define "common link"? I cannot understand how B and A are linked – Iłya Bursov Mar 21 '16 at 17:45
  • are elements in array always sorted and have no gaps? can there be several links? – Iłya Bursov Mar 21 '16 at 17:52
  • Programming language: preferably java but it could be any. – Listy Mar 22 '16 at 05:22
  • By common link I mean a common element amon the lists. In the above example (that I have corrected) A and C lists have nothing in common. So the program searches for a list that has some. B and C have element '6' in common while A and B have element '3' in common. Hence a connection between A and C. – Listy Mar 22 '16 at 05:26
  • Elements are not always sorted or without the gaps. But I can sort them and remove the gaps if it helps. Yes, there can be multiple links the program can list the shortest path or all the possibilities. – Listy Mar 22 '16 at 05:28

1 Answers1

0

to solve this problem you need:

  1. build graph from existing arrays

compare every array with every other array and create edge with weight 1 if at least one element is common, HashSet will help you

  1. find shortest path

as soon as you have graph, you can use any path finding algorithm, I suggest you to start with Floyd–Warshall as simplest one

Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57