Solution from StackExchange, not efficient enough to solve on exercise data.