Problem 565

Abstract / Summary

Given an array of unique integers each from zero to n minus one, find the longest cycle formed by following the value at each index.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0565.py

class Solution:
    def arrayNesting(self, nums: List[int]) -> int:
        result = 1
        todo = set(nums)
        for n in nums:
            if n not in todo:   # already part of another cycle
                continue

            have = set([ n ])
            while True:
                n = nums[n]
                if n in have:   # cycle complete
                    break

                have.add(n)     # current cycle
                todo.discard(n) # numbers are part of exactly one cycle

            result = max(result, len(have))

        return result
20 lines | 591 bytes | submitted October 5, 2023 | GitHub   25% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 57% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Depth First Search
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a method that determines the size of the largest nesting set that can be formed from an integer array where each element points to the next index. A nesting set is built by repeatedly following the value at the current index until a previously visited index is encountered, forming a cycle. The algorithm iterates through the array, explores each distinct cycle exactly once, and tracks the maximum cycle length encountered.

Key Steps

The method begins by establishing a baseline result and a collection of all values that have not yet been assigned to a cycle.

result = 1
todo = set(nums)

It then processes each element in the original order. If the current element has already been removed from the pending set, the loop skips it because it belongs to a cycle that has been fully examined.

for n in nums:
    if n not in todo:   # already part of another cycle
        continue

When an unprocessed element is found, a new temporary set is created to record the indices that belong to the current cycle.

have = set([ n ])

The core of the cycle detection is a while True loop that follows the chain of indices. At each iteration the next index is obtained from the array, and the loop checks whether this index has already been seen in the current cycle. Encountering a repeated index signals that the cycle is complete, and the loop exits.

while True:
    n = nums[n]
    if n in have:   # cycle complete
        break

If the next index is new to the current cycle, it is added to the temporary set, and the same index is removed from the global pending set to guarantee that it will not be revisited in future outer iterations.

    have.add(n)     # current cycle
    todo.discard(n) # numbers are part of exactly one cycle

After the cycle finishes, the algorithm updates the overall maximum length by comparing the size of the just-finished cycle with the current best result.

result = max(result, len(have))

Finally, the method returns the largest cycle size discovered.

return result

Edge Cases Handled

When the input array consists of a single element that points to itself, the initial result of 1 is already correct, and the loop processes the sole element, forming a cycle of length 1.

If the array contains multiple disjoint cycles, the todo set ensures that each element is assigned to exactly one cycle; once an element is removed from todo, any later encounter of that element is ignored, preventing duplicate counting.

Self-referencing indices (where nums[i] == i) are naturally handled: the first iteration adds the index to have, the next lookup yields the same index, the membership test if n in have triggers the break, and the cycle length is recorded as 1.

Arrays where all elements belong to a single large cycle are processed efficiently because the outer loop will skip every subsequent element after the first full traversal, thanks to the early continue when n not in todo.

Performance Optimizations

The algorithm leverages a hash-based set for both the global pending collection (todo) and the per-cycle collection (have). This choice provides constant-time checks for membership and removal, allowing the method to quickly determine whether an element has already been visited or belongs to the current cycle.

By discarding each visited index from todo as soon as it is added to a cycle, the outer loop avoids redundant work; after a cycle is fully explored, all its members are excluded from future consideration, which reduces the number of iterations dramatically for inputs with many small cycles.

The early continue statement at the start of the outer loop acts as a guard that bypasses any work for elements that have already been accounted for, ensuring that the inner while-loop is entered only for the first element of each distinct cycle.

Using a simple integer variable (result) to keep track of the maximum length avoids the need for additional data structures, and the max function updates it in constant time after each cycle.

Overall, the combination of set-based membership tests, immediate removal of processed elements, and minimal auxiliary state yields an implementation that scales well with the size of the input while maintaining clear and direct logic.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big bucket full of numbered cards scattered on the floor. Each card tells you which card to pick up next. You start with one card, look at the number written on it, and jump to that new card. Then you look at that one and jump again. You keep jumping around like this until you eventually land back on a card you have already held.

This little adventure creates a perfect circle of jumps. The code helps you explore all these circles. First, it looks at the pile of all your cards and picks one to start. It keeps track of which cards belong to the circle it is currently exploring so that it does not get confused by cards it has already seen before.

As the jumps happen, the code remembers how many cards are in the circle by counting them up. Whenever a circle finishes, the code checks to see if this new circle is longer than any of the ones found before. It keeps going until every single card has been visited and placed into its own special circle. By the end, it knows the size of the biggest circle found during the whole game.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.12 | σ = 1.34

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fengvyi C++
fpdjsns C++
gouthampradhan Java
JoshCrozier JS
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fengvyi C++
fpdjsns C++
gouthampradhan Java
JoshCrozier JavaScript
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
yuanliu666 Kotlin
zfang399 C++
34 links | 21 authors | 9 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

8 medium 1 hard
10 solutions   October 5, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality