You can use the extra space to help yourself. After sorting the input list, you should do map/dict , where the key is each element in the list, and the value is the list of elements that are divided into a list in the list, so you have something like this, suppose the sorted list is list = [1,2,3,4,5,6] your card will be
1 -> [2,3,4,5,6] 2-> [4,6] 3->[6] 4->[] 5->[] 6->[]
now for each key on the map you find what it can share, and then you find what separates, for example, you know that
1 divides 2 and 2 divides 4 and 6, similarly 1 divides 3 and 3 divides 6
sorting complexity should be O(nlogn) , and list building should be better than O(n^2) (but I'm not sure about this part), and then I'm not sure about complexity when you actually check for factors, but I think it should be much faster than the brute force O(n^3)
If someone can help me understand the time complexity of this, I would really appreciate
EDIT:
You can make the map creation part faster by increasing by X (rather than 1), where X is the number in the list that you are currently using after sorting it.
source share