Leetcode 457. Circular Array Loop
Given an array of integers nums
, you need to determine if there is a loop in nums
. The loop must be a cyclic sequence in which the sum of the elements (the entries within the loop) is strictly greater than zero, and it must be whole. Each element in the array can be used only once. Additionally, you need to ensure the following:
Return true
if there is a loop in nums
, or false
otherwise.
nums
.nums
consists of integers.nums
array and its length?
nums
could be very large, up to 10^4
. Each element in the array can be within the range of smallest negative integer to the largest positive integer within typical C++ integer bounds.0
should directly return false
.#include <vector>
using namespace std;
class Solution {
public:
bool circularArrayLoop(vector<int>& nums) {
int n = nums.size();
auto next_index = [&](int index) {
return ((index + nums[index]) % n + n) % n;
};
for (int i = 0; i < n; ++i) {
if (nums[i] == 0) continue;
int slow = i, fast = i;
bool is_forward = nums[i] > 0;
while (true) {
slow = next_index(slow);
if (is_forward != (nums[slow] > 0) || nums[slow] == 0) break;
fast = next_index(fast);
if (is_forward != (nums[fast] > 0) || nums[fast] == 0) break;
fast = next_index(fast);
if (is_forward != (nums[fast] > 0) || nums[fast] == 0) break;
if (slow == fast) {
if (slow == next_index(slow)) break; // Single-element loop
return true;
}
}
slow = i;
int val = nums[i];
while (nums[slow] != 0) {
int next = next_index(slow);
nums[slow] = 0;
slow = next;
}
}
return false;
}
};
The time complexity is O(n) since each element is visited at most twice:
0
to avoid reprocessing.The space complexity is O(1) as we are using only a few extra variables regardless of the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?