PIXELBANKv9.1.0
Menu

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:

Input:
print(shortest_cycle(["a", "b", "c", "b"]))
Output:
2
Reasoning:
  • 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 3−1=23 - 1 = 2.
  • 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.
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.