Given a list of lists, the task is to write a python program that can convert each sublist to a set and combine to sublists into one set if they have a common element. The output printed will be a list of sets.
Input : test_list = [[15, 14, 12, 18], [9, 5, 2, 1], [4, 3, 2, 1], [19, 11, 13, 12]]
Output : [{11, 12, 13, 14, 15, 18, 19}, {1, 2, 3, 4, 5, 9}]
Explanation : List 1 and list 4 had 12 in common, hence all got merged to one.
Input : test_list = [[15, 14, 12, 18], [9, 5, 2, 1], [4, 3, 2, 1], [19, 11, 13, 22]]
Output : [{18, 12, 14, 15}, {1, 2, 3, 4, 5, 9}, {11, 19, 13, 22}]
Explanation : List 2 and list 3 had 1, 2 in common, hence all got merged to one.
In this, we perform the task of getting all containers having like elements using union(), depending upon conditions. Recursion is used to perform similar task to most lists required.
The original list is : [[15, 14, 12, 18], [9, 5, 2, 1], [4, 3, 2, 1], [19, 11, 13, 12]]
Common element groups : [{11, 12, 13, 14, 15, 18, 19}, {1, 2, 3, 4, 5, 9}]
The approach used in this code is to iterate over each list in the input list, convert it to a set, and then find all other lists that have common elements with it. Then, it merges all the common lists into one set and removes them from the input list. This process is repeated until there are no more lists left in the input list.
Output[{11, 12, 13, 14, 15, 18, 19}, {1, 2, 3, 4, 5, 9}]
Time complexity: O(n^2), where n is the length of the input list test_list. This is because we are iterating over each list in test_list and then iterating over the remaining lists to find the common elements.
Space complexity: O(n^2), where n is the length of the input list test_list. This is because we are creating sets for each list in test_list, and we are also creating a list of common lists for each lst in test_list.