1

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?

allenylzhou
  • 1,431
  • 4
  • 19
  • 36

2 Answers2

1

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.

Community
  • 1
  • 1
Seth
  • 45,033
  • 10
  • 85
  • 120
0

If you start out with your array elements initialized to an invalid value, say -1, then you can stop if an array element has already been assigned, as in the following pseudocode:

if (A[x] == -1)
    A[x] = y
else
    stop
Kevin
  • 590
  • 4
  • 7