Peeking Iterator

medium design iterator

Problem

Design an iterator that supports the peek() operation in addition to next() and hasNext() — peek() returns the next element without consuming it.

Inputiter over [1,2,3]; peek, next, next, peek, next
Output[1, 1, 2, 3, 3]
peek doesn't advance; next does.

class PeekingIterator:
    def __init__(self, iterator):
        self.it = iterator
        self.cache = next(self.it, None)
    def peek(self): return self.cache
    def next(self):
        v = self.cache
        self.cache = next(self.it, None)
        return v
    def hasNext(self): return self.cache is not None
class PeekingIterator {
  constructor(iter) {
    this.iter = iter[Symbol.iterator]();
    this.cache = this.iter.next();
  }
  peek() { return this.cache.value; }
  next() {
    const v = this.cache.value;
    this.cache = this.iter.next();
    return v;
  }
  hasNext() { return !this.cache.done; }
}
class PeekingIterator implements Iterator {
    Iterator it; Integer cache;
    public PeekingIterator(Iterator iter) {
        it = iter; cache = it.hasNext() ? it.next() : null;
    }
    public Integer peek() { return cache; }
    @Override public Integer next() {
        Integer v = cache;
        cache = it.hasNext() ? it.next() : null;
        return v;
    }
    @Override public boolean hasNext() { return cache != null; }
}
class PeekingIterator : public Iterator {
    bool has; int cache;
public:
    PeekingIterator(const vector& nums) : Iterator(nums) {
        has = Iterator::hasNext();
        if (has) cache = Iterator::next();
    }
    int peek() { return cache; }
    int next() { int v = cache; has = Iterator::hasNext(); if (has) cache = Iterator::next(); return v; }
    bool hasNext() const { return has; }
};
Time: O(1) per call Space: O(1)