Note that not all (valid) SNS init configurations result in swaps that can be completed with exactly the minimum required number of direct participants. So solving this problem in general is a bit fiddly.
Here’s the first step towards a general solution: