Memory Limit Exceeded for my Python solution without test example.


  • 0
    V

    My Python solution getting "Memory Limit Exceeded" result. Why do you think it's happening? Is it recursion problem?

    from collections import defaultdict
    
    class SearchResult:
        NotFound, StartsWith, Found = range(3)
    
    class TrieNode:
        # Initialize your data structure here.
        def __init__(self):
            self.children = defaultdict(TrieNode)
            self.leaf_node = False
    
        def insert(self, word):
            if not word:
                self.leaf_node = True
                return
    
            self.children[word[0]].insert(word[1:])
    
        def search(self, word):
            if not word:
                if self.leaf_node:
                    return SearchResult.Found
                else:
                    return SearchResult.StartsWith
    
            if word[0] in self.children:
                return self.children[word[0]].search(word[1:])
            else:
                return SearchResult.NotFound
    
    class Trie:
    
        def __init__(self):
            self.root = TrieNode()
    
        def insert(self, word):
            self.root.insert(word)
    
        def search(self, word):
            if self.root.search(word) == SearchResult.Found:
                return True
    
            return False
    
        def startsWith(self, prefix):
            if self.root.search(prefix) > SearchResult.NotFound: #== SearchResult.StartsWith or  SearchResult.Found:
                return True
    
            return False

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.