Round-Robin Iterator over Iterators
Updated
Problem statement
You are given an array of iterators, where iterators[i] lists the elements that iterator i returns, in order. Build a single round-robin iterator over them:
- The iterators take turns in index order: iterator 0, then 1, then 2, and so on, and after the last one the turns go back to iterator 0.
- On its turn, an iterator contributes exactly one element, its next one.
- An iterator with no elements left is skipped, so its turn goes to the next iterator that still has elements. Empty iterators are skipped from the start.
The round-robin iterator supports two operations:
"next"returns the next element in round-robin order."hasNext"returns whether any element remains. It does not consume anything.
Process operations in order and return one string per operation: the returned element as a decimal string for "next", and "true" or "false" for "hasNext".
Function
roundRobinIterator(iterators: int[][], operations: String[]) → String[]Examples
Example 1
iterators = [[1,2,3],[4],[5,6]]operations = ["next","next","next","next","next","hasNext","next","hasNext"]return = ["1","4","5","2","6","true","3","false"]- Round 1 takes one element from each iterator in order: 1, 4, 5.
- The second iterator is now exhausted and is skipped, so round 2 gives 2 and 6, and round 3 gives 3.
- Before the last
nextone element (3) is left, sohasNextis"true"; after it,hasNextis"false".
Example 2
iterators = [[],[7,8],[]]operations = ["hasNext","next","next","hasNext"]return = ["true","7","8","false"]- Empty iterators are skipped from the start, so only the second iterator contributes: 7, then 8.
Example 3
iterators = [[]]operations = ["hasNext"]return = ["false"]- The only iterator is empty, so there is nothing to return.
Constraints
1 <= iterators.length <= 10000 <= iterators[i].length <= 1000- The iterators hold at most
1000elements in total. -1000 <= iterators[i][j] <= 10001 <= operations.length <= 2000- Each
operations[k]is"next"or"hasNext". "next"is only called when an element remains.
More Bridge interview questions
Similar questions at other companies
- Design Hit CounterNutanix · ONSITE INTERVIEWNutanix interview questions
- Five-Minute Hit CounterGoogle · ONSITE INTERVIEWGoogle interview questions
- Ring Buffer OperationsAmazon · ONSITE INTERVIEW
- Recent Hit CounterAmazon Web Services · ONSITE INTERVIEWAmazon Web Services interview questions
- Design Hit CounterCharta Health · PHONE SCREENCharta Health interview questions
- Constant-Time Weighted Pick with an Alias TableEtched · PHONE SCREEN
- Implement a FIFO QueueByteDance · PHONE SCREENByteDance interview questions
- Stateful Paginated Fetch NLyft · PHONE SCREENLyft interview questions
- Music Player Operation SequenceAtlassian · PHONE SCREENAtlassian interview questions
- Machine Message RouterOpenAI · PHONE SCREENOpenAI interview questions