How to find the index of the next and previous element of a circular array

Ryan Syed
2 min readAug 29, 2018
“low angle photography of white concrete building” by Carl Newton on Unsplash

If you have an array that is circular, i.e. the next element of the last element is the first element.

To find the next and the previous index we are going to rely of the modulus operator.

if N is the array element, curr is the current index in a 0-index array, then
next = (curr + 1) % N

if curr is not the last element then (curr + 1) % N == curr + 1, hence the next index, however if (curr + 1) == N, i.e. the current element is the last index, then (curr + 1) % N == 0, therefore the next element will be the first element of the array.

if N is the array element, curr is the current index in a 0-index array, then
prev = (curr + N - 1) % N

if current is not the first element of the array, then (curr + N — 1) % N == (curr — 1) % N + N % N == curr — 1

However if curr == 0 , i.e. it is the first element, then (curr + N — 1) % N == (N — 1) % N == N — 1 , i.e. the index of the last element of the array.

This article demonstrated how we can craftily use the modulus operator to cover the corner cases while finding the next and previous element in a circular array. For more code walk through and coding tips, check out my other content. Happy coding !!!

--

--