``````from fractions import gcd """ Ah, combinatronics maths, always fun. Let's suppose we have two guards starting with a and b bananas, where we assume a > b Let k be the largest positive integer such that a > (2^k - 1)b If a = b(2^k - 2^(m-1) - 1) or a = b(2^(k+1) - 2^m - 1) for some integer m between 0 and k included then we can match the two guards to play an infinite round of thumb wrestling. We can thus deduce the formula below after development. """ def loops(x, y): res = (x+y)/gcd(x,y) return bool(res & (res - 1)) """ This function might looks like a bottleneck but we need to find a way to update node sizes either way, so i don't think a better way is possible at the time of writing. I might totally be wrong but for our use case arrays won't be bigger than 100 so *shrug* """ def remove(guards, ref): for i in range(len(guards)): j = 0 while j < len(guards[i]): if(guards[i][j]==ref): guards[i].pop(j) j+=1 guards[ref]=[-1] def answer(banana_list): guards= [[] for i in range(len(banana_list))] bad=0 for i in range(len(guards)): for j in range(len(guards)): if(loops(banana_list[i], banana_list[j])): guards[i].append(j) to_process=len(banana_list) while(to_process>0): # we first find the lesser used number min_num=0 for i in range(len(guards)): if(i!=0 and (len(guards[i])