Never Ending Sequence

You are given a list of integers. This list defines a sequence of integers as follows: each element indicates the position in the list of the next element in the sequence. Element 1 of the list is the first element of the sequence, and a 0 indicates the end the sequence.

For example, the list [3, 5, 2, 1, 0] represents the sequence 3, 2, 5 (because the first element of the list is a 3, at position 3 the list contains a 2, at position 2 the list contains a 5, and at position 5 the list contains a 0, ending the sequence). As another example, the list [3, 0, 1] represents the infinite repeating sequence 3, 1, 3, 1, and so on.

The challenge is to develop an algorithm which, given a (finite) list list and an operation to examine the element at the ith position of the list (notated list[i]), can detect if the sequence represented by the list is finite or infinite. However, you are only allowed to use two variables in your algorithm, both integers bounded by the length of the list, and no other variables at all. Futhermore you cannot modify the list. You may assume that every integer in the list refers to a valid position in the list.

Good luck!

[back] [home]