Interview Question


Country: India




Comment hidden because of low score. Click to expand.
0
of 0 vote

class TrieNode {
	char c;
	TrieNode links[];
	boolean fullWord;
	TrieNode(char c)
	{
		this.c=c;
		links=new TrieNode[26];
		fullWord=false;
	}
}

now for insert and printing methods
// root is supposed to be made something like this root=new TrieNode('!');
public static void makeTrie(String s,TrieNode root)
	{
		s=s.toLowerCase();
		TrieNode temp=root;
		for(int i=0;i<s.length();i++)
		{
			int t=s.charAt(i)-'a';
			while(temp.links[t]==null)
			{
				temp=temp.links[t];
				t=s.charAt(++i)-'a';
			}
			if(i!=s.length()-1)
			{
				char c=(char)(t+'a');
				temp.links[t]=new TrieNode(c);
			}
			else
			{
				char c=(char)(t+'a');
				temp.links[t]=new TrieNode(c);
				temp.links[t].fullWord=true;
			}
			temp=temp.links[t];
		}
	}

public static void readTrie(String s,TrieNode root)
	{
		if(s.isEmpty() ||s.equals("!"))
			return;
		TrieNode temp=root;
		String match="";
		int i=0;
		while(i!=s.length())
		{
			int t=s.charAt(i)-'a';
			temp=temp.links[t];
			if(temp==null)
				break;
			match=match+temp.c;
			i++;
		}
		if(match.length()>0)
			match=match.substring(0,match.length()-1);
		printAll(temp,match);
	}
	
	public static void printAll(TrieNode t,String parent)
	{
		if(t==null)
			return;
		
		parent=parent+t.c;
		if(t.fullWord)
			System.out.println(parent);
		for(int i=0;i<26;i++)
			printAll(t.links[i],parent);
	}

- l33t June 21, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

while(temp.links[t]==null)
			{
				temp=temp.links[t];
				t=s.charAt(++i)-'a';

}
shouldn't the condition in while loop be not equal to null?

- Saurabh goyal August 30, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here's an implementation of the Trie. Feel free to ask any questions, I can update the code with more comments

public interface Vocabulary {
    boolean add(String word);
    boolean isPrefix(String prefix);
    boolean contains(String word);
}
public class ListVocabulary implements Vocabulary {
    private List<String> words = new ArrayList<String>();

    /**
     * Constructor that adds all the words and then sorts the underlying list
     */
    public ListVocabulary(Collection<String> words) {
        this.words.addAll(words);
        Collections.sort(this.words);
    }

    public boolean add(String word) {
        int pos = Collections.binarySearch(words, word);
        // pos > 0 means the word is already in the list. Insert only
        // if it's not there yet
        if (pos < 0) {
            words.add(-(pos+1), word);
            return true;
        }
        return false;
    }

    public boolean isPrefix(String prefix) {
        int pos = Collections.binarySearch(words, prefix) ;
        if (pos >= 0) {
            // The prefix is a word. Check the following word, because we are looking 
            // for words that are longer than the prefix
            if (pos +1 < words.size()) {
                String nextWord = words.get(pos+1);
                return nextWord.startsWith(prefix);
            }
            return false;
        }
        pos = -(pos+1);
        // The prefix is not a word. Check where it would be inserted and get the next word.
        // If it starts with prefix, return true.
        if (pos == words.size()) {
            return false;
        }
        String nextWord = words.get(pos);
        return nextWord.startsWith(prefix);
    }

    public boolean contains(String word) {
        int pos = Collections.binarySearch(words, word);
        return pos >= 0;
    }
}

If it helps , there's an implementation with a binary tree as well :

import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;

public class TreeVocabulary extends TreeSet<String> implements Vocabulary {

	private static final long serialVersionUID = 1084215309279053589L;


	public TreeVocabulary() {
		super();
	}

	public TreeVocabulary(Collection<String> c) {
		super(c);
	}

	public boolean isPrefix(String prefix) {
		String nextWord = ceiling(prefix);
		if (nextWord == null) {
			return false;
		}
		if (nextWord.equals(prefix)) {
			Set<String> tail = tailSet(nextWord, false);
			if (tail.isEmpty()) {
				return false;
			}
			nextWord = tail.iterator().next();
		}
		return nextWord.startsWith(prefix);
	}

	/**
	 * There is a mismatch between the parameter types of vocabulary and TreeSet, so
	 * force call to the upper-class method
	 */
	public boolean contains(String word) {
		return super.contains(word);
	}
	@Override
	public String getName() {
		return getClass().getName();
	}
}

- Anonymous June 22, 2014 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More