https://www.codechef.com/viewsolution/51714724
Please check and let me know if you find any test case not working