I solved this problem in leetcode contest, this is the link to solution.
What could be the better way to solve this problem?