Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check there is any forward path in circular cyclic list or not in Python
Suppose we have a circular list called nums where the first and last elements are neighbors. Starting from any index i, we can move nums[i] number of steps forward if nums[i] is positive, or backwards if it's negative. We need to check whether there is a cycle with length greater than one that moves only in one direction (either all forward or all backward).
For example, if the input is nums = [-1, 2, -1, 1, 2], the output will be True because there is a forward path: [1 ? 3 ? 4 ? 1].
Algorithm Steps
To solve this problem, we follow these steps:
- Get the size of nums (n)
- If n is 0, return False
- Create a
seenarray to track visited positions - Normalize nums values using modulo n
- For each starting position, check for uni-directional cycles
- Track direction consistency (forward or backward only)
- Return True if a valid cycle is found, False otherwise
Example
Let's implement the solution to detect uni-directional cycles in a circular array:
def solve(nums):
n = len(nums)
if n == 0:
return False
seen = [0] * n
nums = [x % n for x in nums]
iter_count = 0
for i in range(n):
if nums[i] == 0:
continue
iter_count += 1
pos = True
neg = True
curr = i
while True:
# Check if we found a cycle
if nums[curr] and seen[curr] == iter_count:
return True
# If already visited in a different iteration, break
if seen[curr]:
break
# Check direction consistency
if nums[curr] > 0:
neg = False
else:
pos = False
# If mixed directions, break
if not neg and not pos:
break
# Mark as visited
seen[curr] = iter_count
# Move to next position
curr = (curr + nums[curr] + n) % n
# If next position has 0, break
if nums[curr] == 0:
break
return False
# Test the function
nums = [-1, 2, -1, 1, 2]
print(solve(nums))
The output of the above code is:
True
How It Works
The algorithm works by:
- Normalization: Values are normalized using modulo to handle large steps
-
Direction tracking:
posandnegflags ensure movement is uni-directional - Cycle detection: Using iteration markers to identify when we revisit a position
- Edge cases: Handles zero values which would cause infinite loops
Key Points
- The array is treated as circular (last element connects to first)
- Cycles must be longer than 1 and move in only one direction
- Zero values break the cycle as they don't allow movement
- Each starting position is tested independently
Conclusion
This algorithm efficiently detects uni-directional cycles in circular arrays by tracking visited positions and ensuring consistent movement direction. The time complexity is O(n²) in the worst case, but the iteration marking helps avoid redundant checks.
