#457
Circular Array Loop
MediumArrayHash TableTwo PointersTwo PointersCycle Detection
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a modified version of Floyd's Tortoise and Hare algorithm to detect cycles. It efficiently checks for cycles without needing extra space for tracking visited indices, leveraging the properties of the circular array.
⚙️
Algorithm
3 steps- 1Step 1: Iterate through each index in the array as a potential starting point.
- 2Step 2: For each starting index, use two pointers (slow and fast) to traverse the array according to the movement rules.
- 3Step 3: If slow and fast meet at the same index and the cycle length is greater than 1, return true. If the direction of movement changes, break and start from the next index.
solution.py16 lines
1def circularArrayLoop(nums):
2 n = len(nums)
3 for i in range(n):
4 slow, fast = i, i
5 direction = nums[i] > 0
6 while True:
7 slow = (slow + nums[slow]) % n
8 fast = (fast + nums[fast]) % n
9 fast = (fast + nums[fast]) % n
10 if slow == fast:
11 if slow != (slow + nums[slow]) % n:
12 return True
13 break
14 if (nums[slow] > 0) != direction or (nums[fast] > 0) != direction:
15 break
16 return Falseℹ
Complexity note: This complexity is achieved because each index is processed at most twice (once by slow and once by fast), leading to a linear time complexity.
- 1The direction of movement must remain consistent for a valid cycle.
- 2Using two pointers can significantly reduce the time complexity compared to tracking visited indices.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.