Solution to a practice problem on Hacker Earth