Search⌘ K
AI Features

Circular Array Loop

Explore how to detect cycles in circular arrays using fast and slow pointers. Understand the conditions for a valid loop and implement solutions to identify repeating sequences within array indices.

Statement

There is a circular list of non-zero integers called nums. Each number in the list tells you how many steps to move forward or backward from your current position:

  • If nums[i] is positive, move nums[i] steps forward.

  • If nums[i] is negative, move nums[i] steps backward.

As the list is circular:

  • Moving forward from the last element takes you back to the first element.

  • Moving backward from the first element takes you to the last element.

A cycle in this list means:

  1. You keep moving according to the numbers, and you end up repeating a sequence of indexes.

  2. All numbers in the cycle have the same sign (either all positive or all negative).

  3. The cycle length is greater than 1 (it involves at least two indexes).

Return true if such a cycle exists in the list or false otherwise.

Constraints:

  • 11 \leq nums.length 103\leq 10^3
  • 5000-5000 \leq nums[i] 5000\leq 5000
  • nums[i] !=0!= 0

Examples

canvasAnimation-image
1 / 4

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Circular Array Loop

1.

(True or False) The following array contains a cycle.

[3, -3, 2, -2]

A.

True

B.

False


1 / 5

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6

Try it yourself

Implement your solution in the following coding playground.

JavaScript
usercode > main.js
function circularArrayLoop(nums){
// Replace this placeholder return statement with your code
return false;
}
export {circularArrayLoop}
Circular Array Loop