Python 0457.py
class Solution:
def circularArrayLoop(self, nums: List[int]) -> bool:
def sign(x):
return +1 if x > 0 else -1
size = len(nums)
todo = set() # reference another node
final = set() # self-loops
for i, n in enumerate(nums):
if n % size == 0:
final.add(i)
else:
todo .add(i)
for i in range(size):
if i not in todo: # already done
continue
have = set()
direction = None
while i not in final:
if i in have:
return True
if direction is None: # all steps must have the same sign
direction = sign(nums[i])
have.add(i)
todo.discard(i)
if sign(nums[i]) != direction: # not a cycle since direction changed
break
# next step
i += nums[i]
i %= size
return False
Difficulty
and has an acceptance rate of about 37% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- Two Pointers
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 determines whether a circular array contains a valid loop according to specific rules: the loop must consist of at least two distinct indices, all moves must be in the same direction (all positive or all negative), and the traversal must wrap around the array boundaries. The algorithm separates indices that can never participate in a loop from those that might, then explores each candidate index while tracking visited positions and direction consistency.
Initialization and Classification
The first phase computes the size of the input array and creates two sets. One set, final, records indices that are immediate self-loops because their step value is a multiple of the array length. The other set, todo, holds the remaining indices that still need examination.
size = len(nums)
todo = set() # reference another node
final = set() # self-loops
for i, n in enumerate(nums):
if n % size == 0:
final.add(i)
else:
todo.add(i)
By filtering out indices whose step size is effectively zero modulo the array length, the algorithm eliminates trivial cycles that do not satisfy the “more than one element” requirement.
Main Traversal Loop
The core of the solution iterates over every index. If an index has already been removed from todo, it is skipped because its outcome is already known. For each remaining index, a fresh have set records the path taken during this exploration, and a direction variable captures the required sign of all moves.
for i in range(size):
if i not in todo: # already done
continue
have = set()
direction = None
while i not in final:
if i in have:
return True
...
The inner while loop continues until the traversal reaches a known self-loop (final) or breaks due to a rule violation.
Detecting a Cycle
Inside the loop, the algorithm first checks whether the current index has already been visited in the current path (i in have). Encountering a previously visited index indicates a cycle that satisfies the length requirement, and the function returns True immediately.
if i in have:
return True
Enforcing Consistent Direction
The first step taken from the starting index determines the required direction. Subsequent steps must match this sign; otherwise, the path cannot form a valid loop and the exploration stops.
if direction is None: # all steps must have the same sign
direction = sign(nums[i])
...
if sign(nums[i]) != direction: # not a cycle since direction changed
break
The helper sign function returns +1 for positive numbers and -1 for negative numbers, providing a concise way to compare directions.
Progression and Modulo Wrapping
After confirming direction consistency, the current index is added to the have set and removed from todo to avoid revisiting it in future outer iterations. The next index is computed by adding the current step value and applying modulo arithmetic to wrap around the circular array.
have.add(i)
todo.discard(i)
i += nums[i]
i %= size
Using modulo ensures that the index always stays within bounds, handling both forward and backward jumps uniformly.
Edge Cases Handled
The algorithm explicitly addresses several edge conditions:
- Zero-effective steps: When a step value is a multiple of the array length, the index would never move. Such indices are placed in
finaland never considered for loops, preventing false positives from self-loops of length one. - Direction reversal: If any step in the traversal has a sign opposite to the initial direction, the loop is aborted. This guarantees that only unidirectional cycles are accepted.
- Repeated visits within a single path: Detecting an index already present in
haveconfirms a cycle that involves more than one distinct element, satisfying the problem’s length constraint. - Wrapping behavior: Modulo arithmetic correctly handles jumps that exceed the array bounds in either direction, ensuring the circular nature of the structure is respected.
Performance Optimizations
Several design choices contribute to efficient execution:
- Set-based membership checks: Both
todoandhaveare implemented as hash sets, providing constant-time checks for whether an index has been processed or visited. - Early elimination of impossible candidates: By moving indices with zero-effective steps into
finalbefore the main loop, the algorithm reduces the number of paths it must explore. - In-place removal from
todo: As soon as an index is examined, it is discarded fromtodo. This prevents redundant work in later outer iterations, ensuring each index is processed at most once. - Direction short-circuit: The moment a sign mismatch is detected, the inner loop breaks, avoiding unnecessary traversal of a path that cannot yield a valid cycle.
- Modulo arithmetic for index calculation: Performing the wrap-around with a single modulo operation eliminates the need for conditional branching to handle negative indices or overflow, streamlining the step computation.
Through these mechanisms, the solution efficiently scans the array, quickly discarding dead ends and confirming the existence of a qualifying loop when present.
ELI5 - Simplified Explanation
Imagine a row of tiles arranged in a circle, where each tile has a number written on it. The number tells a player how many steps to hop forward or backward to find the next tile.
The code starts by looking at every tile to see if it lets a player move somewhere else. If a tile says to move zero steps, it is boring because it stays stuck on itself, so that tile is set aside. For all the other tiles, the plan is to follow the hops in a circle.
To find a matching circle of moves, the code starts jumping from tile to tile. It keeps track of which tiles have already been visited during this specific turn. Because the movement has to be consistent, all the hops must go in the same direction, either all clockwise or all counter-clockwise. If a player ever lands back on a tile that was already visited during the current trip, it means a perfect loop has been found. If the path ever hits a tile that was already checked in a previous turn or changes direction, the path is abandoned, and the process starts again with a new tile until all options are explored.
Code Quality
Complexity Analysis
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++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | ||||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| qiyuangong | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| wisdompeak | C++ | |||||||||
| yuanliu666 | Kotlin | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| qiyuangong | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| wisdompeak | C++ | |||||||||
| yuanliu666 | Kotlin |
Videos
Solved On The Same Day
- problem 417: Pacific Atlantic Water Flow
- problem 442: Find All Duplicates in an Array
- problem 554: Brick Wall
- problem 565: Array Nesting
- 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