Google | Phone Screen | Counting Iterator
2584
May 05, 2019
Aug 10, 2019

Given an Iterator<String>, produce an iterator that returns items of type Pair<String, Integer> that return the String retrieved from the original iterator, and the number of times in a row the string appears.

class WordAndCount {
	public String word;
	public int count;
}

class CountingIterator implements Iterator<WordAndCount> {

    public CountingIterator(Iterator<String> words) {  
    }

    public WordAndCount next() {
    }

    public boolean hasNext() {
    }
}

Example:

CountingIterator it = new CountingIterator([foo, foo, foo, bar, foo, bar, bar]);
it.hasNext(); // true
it.next(); // <foo, 3>
it.next(); // <bar, 1>
it.next(); // <foo, 1>
it.next(); // <bar, 2>
it.hasNext(); // false
it.next(); // error
My solution

Java solution using PeekingIterator: https://leetcode.com/playground/DL3y9jQs

Follow-up:
Input is List<Iterator<String>> iterators.

Example:

CountingIterator it = new CountingIterator([foo, foo, foo, bar, foo], [foo, bar], [bar, foo]]);
it.hasNext(); // true
it.next(); // <foo, 3>
it.next(); // <bar, 1>
it.next(); // <foo, 2>
it.next(); // <bar, 2>
it.next(); // <foo, 1>
it.hasNext(); // false
it.next(); // error
Comments (6)