arraysalgorithmindexinglanguage-agnosticcounting

counting array indexes


If I have an array of numbers like [5, 2, 3, 2, 0, 2]

I want to count the number of times I can continuously index the array until we come to an index we already visited, like this:

A[0] = 5 
A[5] = 2
A[2] = 3
A[3] = 2 stop here because we already indexed 2.

So my problem is: without using additional data structure to store the previously visited indices, is there a way I can tell my program when to stop indexing?


Solution

  • It appears that you are treating this array as a directed graph. If that is so, then what you're really asking for is how to detect cycles in a directed graph.

    See:

    To answer your question specifically though: If you were wandering around in a labyrinth, how do you tell if you've been to a particular junction before? You might consider dropping breadcrumbs or unspooling a thread to remind you where you have been. It's the same thing here. You'll need to either annotate your original array with a "visited" flag, or keep a copy of the indexes you've visited in your own array.