Skip to main content

Flatten Iterator

Problem: Given an iterator of iterators, can you give me back an iterator which flattens the given iterator. Ex : Suppose you are given an iterator which has these objects - "1", "2", "3", , , then the flattened iterator returned by you should have "1", "2", "3", "4", "5", "6", "7", "8", "9". Iterators may be nested to any level.


This problem can be solved by implementing a FlattenIterator which takes in the given iterator as an agrument in the constructor and delegating the hasNext() and next() calls to the given iterator using a stack. The given iterator is pushed on to the stack. Nested iterators are pushed on to the stack before traversing and once there are no more elements in the iterator, it is popped from the stack. Here is the code -


import java.util.*;

/**
* User: blogkoder
* Date: Jul 28, 2008
* Time: 9:32:39 PM
*/
public class FlattenIterator implements Iterator
{
private final Stack<Iterator<?>> iterators = new Stack<Iterator<?>>();

private boolean hasNextCalled;
private boolean hasNextValue;
private Object next;

/**
* Default constructor which takes in an iterator.
* @param iterator
* @throws RuntimeException - if iterator is null.
*/
public FlattenIterator(Iterator iterator)
{
if (iterator == null)
{
throw new RuntimeException("Iterator cannot be null.");
}

iterators.push(iterator);
}

public boolean hasNext()
{
boolean hasNext = false;

if (hasNextCalled)
{
hasNext = hasNextValue;
}
else
{
iterateNext();

hasNextCalled = true;

hasNext = (next != null);

hasNextValue = hasNext;
}

return hasNext;
}

private void iterateNext()
{
if (!iterators.empty())
{
if (iterators.peek().hasNext())
{
next = iterators.peek().next();

if (next instanceof Iterator)
{
iterators.push((Iterator) next);

iterateNext();
}
}
else
{
iterators.pop();

iterateNext();
}
}
else
{
next = null;
}
}

public Object next()
{
Object returnValue = null;

if (hasNextCalled)
{
hasNextCalled = false;
returnValue = next;
}
else
{
iterateNext();

returnValue = next;
}

if (returnValue == null)
{
throw new NoSuchElementException();
}

return returnValue;
}

public void remove()
{

}
}

Comments

Popular posts from this blog

Find the number of trailing zeroes in the factorial of a given number.

Problem : Find the number of trailing zeroes in the factorial of a given number. This is an interesting problem. Simple way to solve this is to find the factorial of the number and then count the number of trailing zeroes. But there is a more efficient way to find the number of trailing zeroes, without even finding the factorial of the number. The number of trailing zeroes in 5! is 1, 10! is 2, 15! is 3, 20! is 4, but 25! is 6. Then 30! is 7, 35! is 8, 40! is 9, 45! is 10 but 50! is 12 and so on. So for every multiple of 25, the number of zeroes increases by 2 and for every multiple of 5, the number of zeroes increase by 1. So any number less than 5 has 0 trailing zeroes. Any number between 5 and 10 will have 1 zero, between 10 and 15 will have 2 zeroes and so on. Here is a simple C program implementation of this algorithm. import java.io.BufferedReader; import java.io.InputStreamReader; /** * * @author blogkoder * */ public class TrailingZeroesCalculator { public static void m...

Sum of Subsets - Find how many pairs in the given array sum to a given number

Problem : Given an array of integers intArray[] and another integer sum, find how many pairs of numbers in the given array will sum up to the given sum. This problem is one of the most sought after question in interviews. There may be slight variations of this problem. There are many ways to solve this problem. The most efficient solution considering both time and space complexity is the one discussed below - /** * This will find how many pairs of numbers in the given array sum * up to the given number. * * @param array - array of integers * @param sum - The sum * @return int - number of pairs. */ public static int sumOfSubset(int[] array, int sum) {          // This has a complexity of O ( n lg n )         Arrays.sort(array);         int pairCount = 0;         int leftIndex = 0;         int rightIndex = array.length - 1;          // The portion below has a complextiy of         //  O ( n ) in the worst case.         while (array[rightIndex] >= su...

Prime Numbers

Problem : Given a number, determine if it is prime or not. To determine if a given number is prime or not, you have to check if the given number is divisible by any number other than 1 and itself. If it is, then it is not a prime number.  * In this algorithm, we check if the given number is less than or equal to zero. If it is then it is not a prime number.  * Next we check to see if the given number is 2.  2 is the only even prime number.  * Then we check if the given number is even. If it is, then it is not a prime number.  * Lastly we divide the given number starting from 3 till the square root of the given number.     /**      * This method checks if the given number n is a prime number or not.      *      * @param n - The number to be checked.      * @return boolean      */     public static boolean isPrime(int n)     {         if (n         {             return false;         }         if (n == 2)         {             return true;         }         if (n % 2 == 0)         {     ...