I have solved this problem using inbuilt sort function and by using custom compare function for the 1st test case my ans was coming wrong but when i downloaded the test cases and checked the ans is coming correct then why it was giving wrong ans for first input.
This was the test case which i downloaded 4 ap apple bat batman