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()yieldsarr[startIndex] - Subsequent calls pass a
jumpparameter: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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code