You have N lists
A = [5, 6, 10, 15]
B = [3, 0, 7, 4]
C = [49, 59, 29]
D = [19, 29, 39]
E = [9, 15, 3, 10]
You have to combine them such that: Two lists which have a common elements they should be next to each other. In this case answer is:
A,E,B,C,D
[5, 6, 10, 15, 9, 3, 0, 7, 4, 49, 59, 29, 19, 39]
E comes after A as they have 2 common elements. After E the B comes as they have common elements. B do not have common elements with C or D so anything can come (C or D), lets say C comes. Now C should be followed by D as they have common elements.
Note: This is also acceptable solution
B,E,A,C,D
C,D,A,E,B
....
Thus the main condition is if two lists have common elements they should be next to each other.
Note 2: For simplicity we assume a list can have common elements with maximum 2 other lists. However there can be list which have no common elements with any other list.
Note 3: Output format : preferably both, the name of list and the number sequence.
A,E,B,C,D
or the list of numbers? is it always a single letter identifier before the equals? Please clarify. \$\endgroup\$