educative.io

I don't understand this line: next_index = (current_index + arr[current_index]) % len(arr)

I don’t understand how this line works:
next_index = (current_index + arr[current_index]) % len(arr)

1 Like

Hi Shamim_Imtiaz,
First, you have to understand what the problem statement is. Let me explain,
we have to find: part 1 is to find that, is the array is circular or not.

for example:

Input: [1, 2, -1, 2, 2]
Output: true
Explanation: The array has a cycle among indices: 0 -> 1 -> 3 -> 0

Let me dry run the code:

Taking this line of code in mind : nextIndex = (currentIndex + arr[currentIndex]) % arr.length;

in order to find the next index for index 0:

current_index = 0
value of current index =1
So,
next_index = (0 +1) % 5 => 
The answer will be 1.

As the answer is one we will move 1 step forward. and we will meet the new element that is 2.

For index 1:

current index =1
value of current index is = 2
next_index = (1+ 2) % 5 => 3 % 5=> 3 

As the answer is 3, we will move to index 3 whose value is 2

for index 3:

current index =3
value of current index is = 2
next_index = (3+ 2) % 5 => 5 % 5=> 0 

As the answer is 0, we will move to index 0 whose value is 0

By dry running the code, we come to know a point will come when the next index will be pointing to the start of the array. we can say that this array is circular.

I hope now you will understand how this line is working.
Feel free to ask if you still have any queries.

Best regards,
Educative.