Tries: Contacts

  • + 7 comments

    Hi, I implemented in python 2.7 and am getting Segmentation Fault error on test case 12 only.

    Running my code on my machine works fine and passes test case 12. I understand Segmentation Fault has to do with something like acessing some unallocated memory stack. Is there another definition for Segmentation Fault specific to Hackerrank.

    See code below. Please if you run it and figure out how to pass the test case 12, please kindly share your what you did differently. Thanks

    EDIT: It passes all test cases including test case 12, just add
    slots = ["children","char","is_word","words_count"]

    class Node:
        __slots__ = ["children","char","is_word","words_count"]
    
        def __init__(self,char=None):
            self.char = char
            self.count = 0
            self.children = []
    
    n = int(raw_input().strip())
    
    root = Node()
    def add(contact):
        global root
        node = root
        charNo = 0
        
        for char in contact:
            noOfChildren = len(node.children)
            childIndex = 0
            charNotFound = True
            while childIndex < noOfChildren :
                if char == node.children[childIndex].char:
                    node.children[childIndex].count += 1
                    node = node.children[childIndex]
                    charNotFound = False
                    break
                childIndex += 1
            if charNotFound:
                newCharNode = Node(char)
                newCharNode.count += 1
                node.children.append(newCharNode)
                node = newCharNode
                
    def find(contact):
        global root
        node = root
        previous = None
        charNotFound = True
        for char in contact:
            noOfChildren = len(node.children)
            childIndex = 0 
            charNotFound = True
            while childIndex < noOfChildren:
                if char == node.children[childIndex].char: 
                    node = node.children[childIndex]
                    charNotFound = False
                    break
                childIndex += 1
            if charNotFound:
                return 0
        return node.count
        
    for a0 in xrange(n):
        op, contact = raw_input().strip().split(' ')
        if op == "add":
            add(contact)
        elif op == "find": 
            print find(contact)