Updated code with all testcases fixed