Google Interview Question
Interns Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
Iterator is an interface which each of the collection classes implement in their own way which includes the implementation of the 3 methods mentioned. It appears like you are being asked to create your own collection type because unless you know what your collection looks like, it doesnt make sense to implement these methods.
Please correct me if I'm wrong.
and
public class PeekableIterator<T> implements Iterator<T> {
private final Iterator iterator;
private boolean isPeak = false;
private T nextPeek = null;
public PeekableIterator(Iterator<T> iterator) {
this.iterator = iterator;
}
@Override
public T next() {
if (isPeak) {
isPeak = false;
return peek();
}
return iterator.next();
}
@Override
public void remove() {
iterator.remove();
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
public T peek() {
if (hasNext()) {
if (isPeak == false) {
nextPeek = next();
isPeak = true;
}
} else {
nextPeek = null;
}
return nextPeek;
}
}
and
I present a simple solution in Python below. Using a double-ended queue for O(1) pop/append times.
Solution:
from collections import deque
class PeekIterator:
def __init__(self, nums):
self.result = deque(nums)
def peek(self):
return self.result[0]
def next(self):
return self.result.popleft()
def hasNext(self):
return len(self.result) > 0
Test code:
p = PeekIterator([2,3,6,7,10,12])
while p.hasNext():
print('Elem at top of stack = ', p.peek(), end=', ')
print('and now popping elem using next: ', p.next())
'''
Output:
Elem at top of stack = 2, and now popping elem using next: 2
Elem at top of stack = 3, and now popping elem using next: 3
Elem at top of stack = 6, and now popping elem using next: 6
Elem at top of stack = 7, and now popping elem using next: 7
Elem at top of stack = 10, and now popping elem using next: 10
Elem at top of stack = 12, and now popping elem using next: 12
'''
Good coding question for an interview.
- Anonymous April 05, 2013