Issues with "Stream of Characters"

Hi,
I decided to just ask what I'm doing wrong? I've been at this for over two hours now and still can't figure it out. Also, I am still new to doing algorithms, the school where I got my undergrad didn't do that great of a job at teaching them so I am using other resources.

But, I keep getting an array IndexOutOfRange exception. I have tried two solutions that pass the initial test but for some reason when I try and submit I keep getting this exception thrown. I can't figure out why it's giving me it.

public class StreamChecker {

    public class Trie{
        Trie[] next = new Trie[26];
        bool end;
        
    }

    public Trie root;
    public List<int> query;
    public StreamChecker(string[] words) {
        // Initialize a query list.
        root = new Trie();
        query = new List<int>();
        
        // Loop on words array
        foreach(string s in words){
            char[] c = s.ToCharArray();
            Trie t = root;
            // add the word into trie but in reverse order
            for(int i = c.Length - 1; i >= 0; i--){
                if(t.next[c[i] - 'a'] == null) t.next[c[i] - 'a'] = new Trie();

                t = t.next[c[i]-'a'];
            }
            // mark the end of word
            t.end = true;
        }
            
    }
    
    public bool Query(char letter) {
        // Add the query character into list
        query.Add(letter - 'a');
        Trie t = root;
        // position = size of list - 1
        int i = query.Count - 1;
        

        // while(position >= 0)
        while(i >= 0){
        //  update temp = temp.next[query.Contains(position)]
            t = t.next[query.IndexOf(i)];
        //  if(temp != null and temp is endOfWord)
        //     return true
            if(t != null && t.end){
                return true;
            }
        //  else if (temp = null)
        //     return false
            else if (t == null){
                return false;
            }
        //  position--;
            i--;
        }
        // return false
        return false;
    }

    

}
Comments (0)