DEV Community

SalahElhossiny
SalahElhossiny

Posted on

3 2

Leetcode Solutions: Implement Tree (Prefix Tree)

Here is the problem:

A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

Implement the Trie class:

Trie() Initializes the trie object.
void insert(String word) Inserts the string word into the trie.
boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.

Here is my different solution:

class Trie(object):

    def __init__(self):
        self.words = []


    def insert(self, word):
        """
        :type word: str
        :rtype: None
        """
        self.words.append(word)


    def search(self, word):
        """
        :type word: str
        :rtype: bool
        """
        for w in self.words:
            if w == word:
                return True
        return False


    def startsWith(self, prefix):
        """
        :type prefix: str
        :rtype: bool
        """
        for w in self.words:
            if w.startswith(prefix):
                return True
        return False




Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay