import java.util.ArrayList;

/**
 * Write a description of class Lexicon here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Lexicon
{	private static final int NUM_LETTERS = 26;
	private static final int A_VALUE = (int)'a';

	private ArrayList myWords;

	public Lexicon()
	{	myWords = new ArrayList();
		for(int i = 0; i < NUM_LETTERS; i++)
			myWords.add(new ArrayList());
	}

	// pre: word is all lowerCase and starts with a letter
	//	words sent in alphabetical order
	// post: word inserted in lexicon
	public void addWord(String word)
	{	int index = (int)word.charAt(0) - A_VALUE;
		((ArrayList)myWords.get(index)).add(word);
	}

	//pre: word != null
	//post: returns true if word is in the lexicon.
	//Note, this methd is case sensitive
	public boolean wordIsPresent(String word)
	{	return binarySearch(word, false);	}

	//pre: prefix != null
	//post: returns true if the prefix starts at leat one word in the lexicon
	public boolean isValidPrefix(String prefix)
	{	return binarySearch(prefix, true);	}	

	private boolean binarySearch(String word, boolean prefixOnly)
	{	int index = (int)word.charAt(0) - A_VALUE;
		if( index < 0 || index > NUM_LETTERS)
			return false;
		boolean found = false;
		int first = 0;
		int last = ((ArrayList)myWords.get(index)).size() - 1;
		int mid;
		String temp;
		while(!found && first <= last)
		{	mid = (first + last) / 2;
			temp = (String)(((ArrayList)myWords.get(index)).get(mid));
			if( prefixOnly && (temp.length() > word.length()) )
				temp = temp.substring(0, word.length());
			if( word.compareTo(temp) < 0 )
				last = mid -1;
			else if ( word.compareTo(temp) >  0 )
				first = mid + 1;
			else
				found = true;
		}
		return found;
	}		
}
