Simple Java Solution using Cached Value 107ms

  • 3
    class PeekingIterator implements Iterator<Integer> {
        private Integer nextCachedVal = null;
        private Iterator<Integer> iterator;
    	public PeekingIterator(Iterator<Integer> iterator) {
    	    // initialize any member here.
    	    this.iterator = iterator;
    	    next(); // cache the next value if any
        // Returns the next element in the iteration without advancing the iterator.
    	public Integer peek() {
            return nextCachedVal;
    	// hasNext() and next() should behave the same as in the Iterator interface.
    	// Override them if needed.
    	public Integer next() {
    	    Integer retVal = nextCachedVal;
    	    nextCachedVal = iterator.hasNext() ? : null;
    	    return retVal;
    	public boolean hasNext() {
    	    return (nextCachedVal != null);

  • 0

    Change "Integer" to "E" to support Generics

  • 0

    awesome solution!!

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.