We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Generate Circular Array Values

Number: 2814

Difficulty: Medium

Paid? Yes

Companies: N/A


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.


Code Solutions

def cycleGenerator(arr, startIndex):
    # Initialize current index with startIndex.
    current_index = startIndex
    # Yield the first element from the starting index.
    yield arr[current_index]
    # Continuously accept a jump value and yield the next element.
    while True:
        # Receive the jump value.
        jump = (yield)
        # Adjust current_index using modular arithmetic to wrap around.
        current_index = (current_index + jump) % len(arr)
        # Yield the value at the new index.
        yield arr[current_index]

# Example usage:
if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5]
    gen = cycleGenerator(arr, 0)
    print(next(gen))         # Output: 1
    print(gen.send(1))       # Output: 2
    print(gen.send(2))       # Output: 4
    print(gen.send(6))       # Output: 5
← Back to All Questions