Imagine you're following a treasure map where each location points to another location, and you want to find the longest possible path before returning to a place you've already visited!
You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n-1]. Think of each index as a location, and each value as directions to the next location.
For any starting index k, you can build a set s[k] by following this path:
- Start at
nums[k] - Next, go to
nums[nums[k]] - Then
nums[nums[nums[k]]] - Continue until you would revisit a number you've already seen
Goal: Return the maximum length of any such set s[k].
Example: If nums = [5,4,0,3,1,6,2], starting from index 0: we get 5 → 6 → 2 → 0 → 5 (length 4 before repeating).
Input & Output
Visualization
Time & Space Complexity
Each element is visited exactly once across all iterations
Only need a boolean visited array of size n, or can modify input array
Constraints
- 1 ≤ nums.length ≤ 105
- 0 ≤ nums[i] < nums.length
- nums is a permutation of numbers [0, 1, ..., n-1]
- All integers nums[i] are unique