2757. Generate Circular Array Values π
Description
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], steps = [1,2,6], startIndex = 0 Output: [1,2,4,5] Explanation: Β Β const gen = cycleGenerator(arr, startIndex); Β gen.next().value; Β // 1, index = startIndex = 0 Β gen.next(1).value; // 2, index = 1, 0 -> 1 Β gen.next(2).value; // 4, index = 3, 1 -> 2 -> 3 Β gen.next(6).value; // 5, index = 4, 3 -> 4 -> 0 -> 1 -> 2 -> 3 -> 4
Example 2:
Input: arr = [10,11,12,13,14,15], steps = [1,4,0,-1,-3], startIndex = 1 Output: [11,12,10,10,15,12] Explanation: Β const gen = cycleGenerator(arr, startIndex); Β gen.next().value; Β // 11, index = 1 Β gen.next(1).value; // 12, index = 2 Β gen.next(4).value; // 10, index = 0 Β gen.next(0).value; // 10, index = 0 Β gen.next(-1).value; // 15, index = 5 Β gen.next(-3).value; // 12, index = 2
Example 3:
Input: arr = [2,4,6,7,8,10], steps = [-4,5,-3,10], startIndex = 3 Output: [7,10,8,4,10] Explanation: Β Β const gen = cycleGenerator(arr, startIndex); Β gen.next().value Β // 7, index = 3 Β gen.next(-4).value // 10, index = 5 Β gen.next(5).value // 8, index = 4 Β gen.next(-3).value // 4, index = 1 Β Β gen.next(10).value // 10, index = 5
Β
Constraints:
1 <= arr.length <= 1041 <= steps.length <= 100-104Β <= steps[i],Β arr[i] <= 1040 <= startIndex <Β arr.length
Solutions
Solution 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |