This code executes all test cases but gives partially wrong results on some