LIst index out of range

The following problem is on GFG it seems to work on the test cases i’ve used but when i try to submit it , it shows list index out of range

link to problem: https://practice.geeksforgeeks.org/problems/minimum-swaps-required-to-bring-all-elements-less-than-or-equal-to-k-together4847/1#

link to solution: https://ide.geeksforgeeks.org/rC526fVHLa

Thanks for the help

The if condition on line 5 is executed only once as it is not a part of the while loop, so put that condition inside the while loop condition itself so that it gets checked everytime you access arr[i+1]

i’ve tried using that also but it is not working giving me the same output
here the link to the solution.

https://ide.geeksforgeeks.org/BfGFENM1q6

the conditions are checked in sequence so check if i is within bounds BEFORE you use it as an index

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

NO you didn’t cleared my doubt, can you please fix my code.

@pewpiyu change line 5 to this
while arr[i]<=k and i < n-1 and arr[i+1] <= k: