Generate Circular Array Values - Problem

Imagine you're building a circular playlist navigator that can jump around tracks in a loop! ๐ŸŽต

Given a circular array arr and an integer startIndex, you need to create a generator object that yields values from the array. Think of it as a smart pointer that can jump around a circular track.

How it works:

  • First call to gen.next() yields arr[startIndex]
  • Subsequent calls pass a jump parameter: gen.next(jump)
  • Positive jump: Move forward, wrapping to start if at end
  • Negative jump: Move backward, wrapping to end if at start

The array behaves like a circular track where the last element connects back to the first!

Input & Output

example_1.js โ€” Basic Forward Jump
$ Input: arr = [1, 2, 3, 4, 5], startIndex = 2 gen.next() // First call gen.next(3) // Jump forward by 3
โ€บ Output: 3 (initial) 1 (after jump)
๐Ÿ’ก Note: Start at index 2 (value 3). Jump forward by 3: (2+3)%5 = 0, so we land at index 0 (value 1)
example_2.js โ€” Negative Jump with Wrap
$ Input: arr = [1, 2, 3, 4, 5], startIndex = 1 gen.next() // First call gen.next(-2) // Jump backward by 2
โ€บ Output: 2 (initial) 5 (after jump)
๐Ÿ’ก Note: Start at index 1 (value 2). Jump backward by 2: (1-2)%5 = -1, which becomes index 4 (value 5) after handling negative result
example_3.js โ€” Large Jump
$ Input: arr = [10, 20, 30], startIndex = 0 gen.next() // First call gen.next(7) // Large forward jump
โ€บ Output: 10 (initial) 20 (after jump)
๐Ÿ’ก Note: Start at index 0 (value 10). Jump forward by 7: (0+7)%3 = 1, so we land at index 1 (value 20). Large jumps wrap around multiple times.

Constraints

  • 1 โ‰ค arr.length โ‰ค 104
  • 0 โ‰ค startIndex < arr.length
  • -109 โ‰ค jump โ‰ค 109
  • Array elements can be any integer values
  • Generator should handle unlimited jumps

Visualization

Tap to expand
Circular Generator NavigationABCDEFJump +2Result: (0+2)%6=2Modular Arithmetic MagicDirect calculation - no counting needed!
Understanding the Visualization
1
Initialize Generator
Set starting position and prepare to yield values
2
Calculate Jump
Use modular arithmetic: (current + jump) % length
3
Handle Negatives
Add array length if result is negative
4
Yield Value
Return value at calculated position
Key Takeaway
๐ŸŽฏ Key Insight: Modular arithmetic transforms a potentially O(n) step-counting problem into an elegant O(1) direct calculation, making the generator efficient even for massive jumps.
Asked in
Google 25 Meta 18 Amazon 15 Microsoft 12
28.4K Views
Medium Frequency
~15 min Avg. Time
945 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen