First version, works but 'Memory Limit Exceeded'