Use loops and sets intersection instead of recursion