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:

This error basically means you are trying to access a value at a List index which is out of bounds i.e greater than the last index of the list or less than the least index in the list. So the first element is 0, second is 1, so on. So if there are n elements in a python list, the last element is n-1 . If you try to access the empty or None element by pointing available index of the list, then you will get the "List index out of range " error. To solve this error, you should make sure that you’re not trying to access a non-existent item in a list.

An index in Python refers to a position within an ordered list . To retrieve an element of the list, you use the index operator ([]) . Using indexing you can easily get any element by its position.