I'm not convinced that this is the best solution. If feels over engineered, and on top of that I'm not convinced that the solution provided is correct. Did you have any unit tests which I could go over with your function?