This is a sudo code solution for the problem