Problem Description
Given a circular array arr and an integer startIndex, create a generator that yields values from arr. The first call to next() returns arr[startIndex]. Every subsequent next() accepts an integer jump that tells how far to move from the current index. The index wraps around the array: for a positive jump, move right and wrap from the end to the beginning; for a negative jump, move left and wrap from the beginning to the end.
Key Insights
- Use modular arithmetic to handle the circular wrapping of the index.
- Maintain a current index that is updated on each generator call.
- The generator should start by yielding the element at the starting index.
- Subsequent calls update the index before yielding the corresponding array element.
- Both positive and negative jumps are processed uniformly with the modulo operator.
Space and Time Complexity
Time Complexity: O(1) per call, since only arithmetic operations are performed. Space Complexity: O(1), as only a few variables are used for tracking the index and state.
Solution
Implement a generator that initializes the current index to startIndex and yields arr[startIndex] immediately. For every subsequent call, retrieve the jump passed to next(), update the current index using modular arithmetic (taking care to handle negative values correctly), and yield the element at the updated index. This approach ensures that the generator continuously loops over the array in a circular manner.