Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
1 <= arr.length <= 10^4
1 <= steps.length <= 100
-10^4 <= steps[i], arr[i] <= 10^4
0 <= startIndex < arr.length
Solution
Method 1 – Generator with Circular Indexing
Intuition
We need to yield values from a circular array, starting at a given index, and move forward or backward by a given jump. The index should wrap around the array boundaries, so we use modulo arithmetic to handle circular movement.
Approach
- Define a generator function that takes
arr
andstartIndex
. - Initialize the current index to
startIndex
. - On the first call to
next()
, yieldarr[startIndex]
. - On each subsequent call, receive a
jump
value:- If
jump
is positive, move forward byjump
(with wrap-around). - If
jump
is negative, move backward byabs(jump)
(with wrap-around).
- If
- Yield the value at the new index each time.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
per operation, as each jump and yield is constant time. - 🧺 Space complexity:
O(1)
, as only a few variables are used.