My solution and submission to HackerEarth.com