Detect Repeated State Cycles in a Trajectory
Problem Statement
An agent revisiting the same environment state is likely looping. Given a trajectory of state hashes, find the length of the shortest cycle (distance between two equal states), or 0 if no state repeats.
Background
Scan the state sequence keeping the last index each state was seen. When a state recurs at index j having been seen at i, the cycle length is j - i. Return the minimum such length across the trajectory; 0 if all states are distinct.
Your Task
def shortest_cycle(states):
Return the shortest repeat distance, or 0.
Input Format
- states (list of hashable state ids).
Output Format
- A single int.
Sample
print(shortest_cycle(["a", "b", "c", "b"]))
Output:
2
Example
print(shortest_cycle(["a", "b", "c", "b"]))
2
- Initialize a tracker for the last seen index of each state and set the best cycle length to 0, preparing to scan the sequence
["a", "b", "c", "b"]. - Process the first three states
"a","b", and"c"at indices 0, 1, and 2; since none have appeared before, record their indices in the tracker without updating the cycle length. - Encounter state
"b"again at index 3; look up its previous index (1) to calculate the distance . - Compare this distance (2) against the current best (0); since 2 is smaller than infinity (or the initial zero flag indicating no cycle found), update the best cycle length to 2.
- The final output is 2
Constraints
- Cycle length is the index gap between consecutive equal states.
- Track the most recent index of each state.
- Return 0 if no state repeats.