Skip to content

Commit 149e41b

Browse files
committed
Runtime: 0 ms (Top 100.0%) | Memory: 8.00 MB (Top 36.07%)
1 parent 7bb7f9b commit 149e41b

File tree

1 file changed

+32
-34
lines changed

1 file changed

+32
-34
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,40 @@
1+
// Runtime: 0 ms (Top 100.0%) | Memory: 8.00 MB (Top 36.07%)
2+
13
class Solution {
24
public:
5+
6+
int next(vector<int>& nums, int i){
7+
int n = nums.size();
8+
return (n+nums[i]+i)%n;
9+
}
10+
311
bool circularArrayLoop(vector<int>& nums) {
4-
unordered_set<int>us;
5-
for(int i{0};i<nums.size() && us.find(i)==us.end();i++){
6-
unordered_map<int,int>um;
7-
int index=0;
8-
int j=i;
9-
um[i];
10-
bool flag1=0,flag2=0;
11-
while(true){
12-
if(nums.at(i)<0){
13-
index=(nums.size()+nums.at(j)+j)%nums.size();
14-
flag1=1;
15-
}else{
16-
index=(nums.at(j)+j)%nums.size();
17-
flag2=1;
18-
}
19-
if(nums.at(index)>0 && flag1==1){
20-
break;
21-
}else if(nums.at(index)<0 && flag2==1){
22-
break;
23-
}
24-
if(um.find(index)==um.end()){
25-
um[index];
26-
us.insert(index);
27-
}else{
28-
if(j==index){
29-
break;
30-
}
31-
if(um.size()>1){
32-
return true;
33-
}else{
34-
break;
35-
}
12+
int n = nums.size();
13+
// we can use slow and fast pointer to check whether there is loop or not
14+
for(int &num: nums)
15+
num %= n;
16+
for(int i=0;i<n;i++){
17+
int slow = i,
18+
fast = i;
19+
while(nums[slow]*nums[next(nums,fast)]>0 && nums[slow]*nums[next(nums,next(nums,fast))]>0){
20+
slow = next(nums,slow);
21+
fast = next(nums,next(nums,fast));
22+
if(slow==fast){
23+
if(slow==next(nums,slow)) // single length
24+
return false;
25+
return true;
3626
}
37-
j=index;
38-
}
27+
}
28+
/// DONOT TRAVERSE WHERE THERE IS NO PATH TO GET LOOP.
29+
int j = i;
30+
int val = nums[i];
31+
while (nums[j] * val > 0) {
32+
int nexx = next(nums,j);
33+
nums[j] = 0;
34+
j = nexx;
35+
}
3936
}
37+
4038
return false;
4139
}
4240
};

0 commit comments

Comments
 (0)