Can anyone cast a more experience eye over this? It works with many examples but it is timing out on the server. I have use recursion for this solution and I've tried to make it as readable as possible. Have I over engineered this?