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?

1
  • I am personally finding this question to be unclear. What programming language is this to be solved with? Commented Mar 7, 2024 at 5:58

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.