Circular Array Loop – LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
You are playing a game involving a circular array of non-zero integers nums
. Each nums[i]
denotes the number of indices forward/backward you must move if you are located at index i
:
- If
nums[i]
is positive, movenums[i]
steps forward, and - If
nums[i]
is negative, movenums[i]
steps backward.
Since the array is circular, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element.
A cycle in the array consists of a sequence of indices seq
of length k
where:
- Following the movement rules above results in the repeating index sequence
seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ...
- Every
nums[seq[j]]
is either all positive or all negative. k > 1
Return true
if there is a cycle in nums
, or false
otherwise.
Example 1:
Input: nums = [2,-1,1,2,2] Output: true Explanation: There is a cycle from index 0 -> 2 -> 3 -> 0 -> ... The cycle's length is 3.
Example 2:
Input: nums = [-1,2] Output: false Explanation: The sequence from index 1 -> 1 -> 1 -> ... is not a cycle because the sequence's length is 1. By definition the sequence's length must be strictly greater than 1 to be a cycle.
Example 3:
Input: nums = [-2,1,-1,-2,-2] Output: false Explanation: The sequence from index 1 -> 2 -> 1 -> ... is not a cycle because nums[1] is positive, but nums[2] is negative. Every nums[seq[j]] must be either all positive or all negative.
Constraints:
1 <= nums.length <= 5000
-1000 <= nums[i] <= 1000
nums[i] != 0
C++ Circular Array Loop LeetCode Solution
class Solution {
public:
int next(vector<int>& nums, int i){
int n = nums.size();
return (n+nums[i]+i)%n;
}
bool circularArrayLoop(vector<int>& nums) {
int n = nums.size();
// we can use slow and fast pointer to check whether there is loop or not
for(int &num: nums)
num %= n;
for(int i=0;i<n;i++){
int slow = i,
fast = i;
while(nums[slow]*nums[next(nums,fast)]>0 && nums[slow]*nums[next(nums,next(nums,fast))]>0){
slow = next(nums,slow);
fast = next(nums,next(nums,fast));
if(slow==fast){
if(slow==next(nums,slow)) // single length
return false;
return true;
}
}
/// DONOT TRAVERSE WHERE THERE IS NO PATH TO GET LOOP.
int j = i;
int val = nums[i];
while (nums[j] * val > 0) {
int nexx = next(nums,j);
nums[j] = 0;
j = nexx;
}
}
return false;
}
};
Java Circular Array Loop LeetCode Solution
public class Solution {
public boolean circularArrayLoop(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; i++) {
if (nums[i] == 0) {
continue;
}
// slow/fast pointer
int j = i, k = getIndex(i, nums);
while (nums[k] * nums[i] > 0 && nums[getIndex(k, nums)] * nums[i] > 0) {
if (j == k) {
// check for loop with only one element
if (j == getIndex(j, nums)) {
break;
}
return true;
}
j = getIndex(j, nums);
k = getIndex(getIndex(k, nums), nums);
}
// loop not found, set all element along the way to 0
j = i;
int val = nums[i];
while (nums[j] * val > 0) {
int next = getIndex(j, nums);
nums[j] = 0;
j = next;
}
}
return false;
}
public int getIndex(int i, int[] nums) {
int n = nums.length;
return i + nums[i] >= 0? (i + nums[i]) % n: n + ((i + nums[i]) % n);
}
}
Python 3 Circular Array Loop LeetCode Solution
class Solution(object):
def circularArrayLoop(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums or len(nums) < 2:
return False
n = len(nums)
for i in range(n):
if type(nums[i]) != int: # visited element
continue
if nums[i] % n == 0: # self-loop
continue
direction = (nums[i] > 0) # loop direction, cannot be changed midway
mark = str(i)
while (type(nums[i]) == int) and (direction ^ (nums[i] < 0)) and (nums[i] % n != 0):
jump = nums[i]
nums[i] = mark
i = (i + jump) % n
if nums[i] == mark:
return True
return False
Array-1180
String-562
Hash Table-412
Dynamic Programming-390
Math-368
Sorting-264
Greedy-257
Depth-First Search-256
Database-215
Breadth-First Search-200
Tree-195
Binary Search-191
Matrix-176
Binary Tree-160
Two Pointers-151
Bit Manipulation-140
Stack-133
Heap (Priority Queue)-117
Design-116
Graph-108
Simulation-103
Prefix Sum-96
Backtracking-92
Counting-86
Sliding Window-73
Linked List-69
Union Find-66
Ordered Set-48
Monotonic Stack-47
Recursion-43
Trie-41
Binary Search Tree-40
Divide and Conquer-40
Enumeration-39
Bitmask-37
Queue-33
Memoization-32
Topological Sort-31
Geometry-30
Segment Tree-27
Game Theory-24
Hash Function-24
Binary Indexed Tree-21
Interactive-18
Data Stream-17
String Matching-17
Rolling Hash-17
Shortest Path-16
Number Theory-16
Combinatorics-15
Randomized-12
Monotonic Queue-9
Iterator-9
Merge Sort-9
Concurrency-9
Doubly-Linked List-8
Brainteaser-8
Probability and Statistics-7
Quickselect-7
Bucket Sort-6
Suffix Array-6
Minimum Spanning Tree-5
Counting Sort-5
Shell-4
Line Sweep-4
Reservoir Sampling-4
Eulerian Circuit-3
Radix Sort-3
Strongly Connected Componen-t2
Rejection Sampling-2
Biconnected Component-1