Hello again guys,
Thanks for the helps and suggestions so far especially @etienne_dg and @Henrique_Becker.
Ultimately, after trying a bunch of different ways, I realise now that trying to detect shared ancestors wasn’t quite what I should’ve done.
On a higher level, the method I was trying to use on these graphs only works on tree structured graphs. So instead of trying to detect cycles, I am now going to find a way to convert the original graph J first into joint/clique tree by moralization and then triangulation to form cliques.
Thanks again for the helps.