1046. Generate Circular Array values

Given a circular array arr and an integer startIndex, return a generator object gen that yields values from arr.

The first time gen.next() is called on the generator, it should should yield arr[startIndex].

Each subsequent time gen.next() is called, an integer jump will be passed into the function (Ex: gen.next(-3)).

  • If jump is positive, the index should increase by that value, however if the current index is the last index, it should instead jump to the first index.
  • If jump is negative, the index should decrease by the magnitude of that value, however if the current index is the first index, it should instead jump to the last index.

Example 1:

Input : arr = [1, 2, 3, 4, 5] , jumps = [1, 3, 8] , startIndex = 2

Output : [3, 4, 2, 5]

Explanation :

const gen = cycleGenerator(arr, startIndex);

 gen.next().value; // 3, index = startIndex = 2

 gen.next(1).value; // 4, index = 3, 2 -> 3

 gen.next(3).value; // 2, index = 1, 3 -> 4 -> 0 -> 1

 gen.next(8).value; // 5, index = 4, 1 -> 2 -> 3 -> 4 -> 0 -> 1 -> 2 -> 3 -> 4

Example 2:

Input : arr = [1, 2, 3, 4, 5, 6] , jumps = [4, -1, -6, 2, 5] , startIndex = 0

Output : [1, 5, 4, 4, 6, 5]

Explanation :

const gen = cycleGenerator(arr, startIndex);

 gen.next().value; // 1, index = startIndex = 0

 gen.next(4).value; // 5, index = 4, 0 -> 1 -> 2 -> 3 -> 4

 gen.next(-1).value; // 4, index = 3, 4 -> 3

 gen.next(-6).value; // 4, index = 3, 3 -> 2 -> 1 -> 0 -> 5 -> 4 -> 3

gen.next(2).value; // 6, index = 5, 3 -> 4 -> 5

gen.next(5).value; // 5, index = 4, 5 -> 0 -> 1 -> 2 -> 3 -> 4

Now Your Turn!

Pick the correct output for the given input

Input : arr = [1, 2, 3, 4, 5] , jumps = [4, -4, 5, -10], startIndex = 1

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= arr.length <= 104
  • 1 <= steps.length <= 100
  • -104 <= steps[i], arr[i] <= 104
  • 0 <= startIndex < arr.length

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution{
cycleGenerator = function* (arr, startIndex) {
//your code goes here
};
}
Test Case

Input:

Arr
Jumps
Start Index