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
Difficulty
and has an acceptance rate of about 57% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Depth First Search
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 339: Nested List Weight Sum
- problem 341: Flatten Nested List Iterator
- problem 364: Nested List Weight Sum II
Solved On The Same Day
- problem 417: Pacific Atlantic Water Flow
- problem 442: Find All Duplicates in an Array
- problem 457: Circular Array Loop
- problem 554: Brick Wall
- problem 647: Palindromic Substrings
- problem 721: Accounts Merge
- problem 785: Is Graph Bipartite?
- problem 1061: Lexicographically Smallest Equivalent String
- problem 273: Integer to English Words
Extra
- 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