דילוג לתוכן הראשי
36

Implement Trie (Prefix Tree)

בינוניtriedesign

הקוד שלכם עדיין לא נשמר: רענון או יציאה מהדף מאפסים אותו. שמירת התקדמות תגיע יחד עם חשבונות משתמשים.

התרגיל הזה משתמש ב:Triesקראו את המדריך למתחילים

ממשו trie (נקרא גם prefix tree, ומבוטא "טריי"): מבנה ששומר מילים כך שחיפוש מילה, או בדיקה אם מילה כלשהי מתחילה בתחילית (prefix) מסוימת, הוא מהיר.

ממשו את המחלקה Trie:

  • new Trie() יוצרת trie ריק.
  • insert(word) מוסיפה את word.
  • search(word) מחזירה true אם word הוכנסה, אחרת false.
  • startsWith(prefix) מחזירה true אם מילה כלשהי שהוכנסה מתחילה ב-prefix.

הבנת הבעיה

  • תחילית (prefix) היא ההתחלה של מילה: "app" היא תחילית של "apple". כל מילה היא גם תחילית של עצמה.
  • search צריכה מילה מדויקת: אחרי הכנסה של "apple" בלבד, search("app") הוא false.
  • startsWith צריכה רק שמילה כלשהי תתחיל כך: startsWith("app") הוא true.
  • תחשבו על השלמה אוטומטית: כשמקלידים "app", היא צריכה לדעת מהר אילו מילים מתחילות כך.

דוגמה 1

text
ops:      ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
args:     [[],     ["apple"], ["apple"], ["app"], ["app"],       ["app"],  ["app"]]
expected: [null,   null,      true,      false,   true,          null,     true]
  • search("apple") ← true: היא הוכנסה.
  • search("app") ← false: עד עכשיו הוכנסה רק "apple".
  • startsWith("app") ← true: "apple" מתחילה ב-"app".
  • אחרי insert("app"), search("app") ← true.

איך הטסטים עובדים: כל טסט הוא רצף של קריאות. ops נותן שם לכל קריאה (הראשונה יוצרת את האובייקט), args מחזיק את הארגומנטים, ו-expected את ערכי ההחזרה (null לקריאות שלא מחזירות כלום).

אילוצים

  • 1 <= word.length, prefix.length <= 2000
  • מילים ותחיליות מכילות רק אותיות אנגליות קטנות.
  • לכל היותר 3 * 10^4 קריאות בסך הכל.

רמזים

נתקעתם? פתחו רמז אחד בכל פעם. כל רמז מגלה קצת יותר מהקודם.

    הרעיון במשפט אחד

    שומרים מילים כמסלולים בעץ שבו כל צעד הוא אות אחת, ומסמנים את ה-nodes שבהם מילה נגמרת; כל פעולה היא אז הליכה למטה לאורך האותיות.

    הגישה הנאיבית (ולמה היא איטית)

    שומרים את כל המילים במערך (או ב-set).

    • search(word): set עושה את זה מהר. בסדר.
    • startsWith(prefix): צריך לבדוק כל מילה שמורה כדי לראות אם היא מתחילה בתחילית. עם 30,000 מילים, זה איטי בכל קריאה.

    התובנה המרכזית

    מילים שמתחילות באותה דרך יכולות לחלוק את ההתחלה שלהן. שומרים את האותיות כעץ, שבו כל קשת היא אות:

    טוען דיאגרמה...

    ה-trie הזה מחזיק את car, card ו-care. לכל node יש:

    • children: map מאות ל-node הבא.
    • isEnd: true אם מילה נגמרת ב-node הזה (ה-nodes שמסומנים "end").

    עכשיו כל פעולה היא רק הליכה למטה לאורך האותיות, והמחיר שלה תלוי רק באורך המילה, לא בכמה מילים שמורות.

    פעולההולכים על האותיות...תשובה
    insert(word)ויוצרים כל ילד חסר בדרךמסמנים את ה-node האחרון isEnd
    search(word)אם אות חסרה, עוצרים: falseה-isEnd של ה-node האחרון
    startsWith(prefix)אם אות חסרה, עוצרים: falsetrue (להגיע לסוף מספיק)

    צעד אחר צעד

    הקריאות מדוגמה 1:

    קריאההליכהתוצאה
    insert("apple")יוצרים a → p → p → l → e, מסמנים את e כסוף
    search("apple")הולכים ל-e, שהוא סוףtrue
    search("app")הולכים ל-p השני, שהוא לא סוףfalse
    startsWith("app")הולכים ל-p השני: המסלול קייםtrue
    insert("app")המסלול קיים; מסמנים את ה-p השני כסוף
    search("app")הולכים ל-p השני, שעכשיו הוא סוףtrue

    הקוד

    הפתרון לדוגמה מופיע למטה, עם הערות על כל שורה חשובה.

    כמה זה מהיר?

    כש-L = האורך של המילה או התחילית:

    • זמן: O(L) לכל קריאה, לא משנה כמה מילים שמורות.
    • זיכרון: O(סך כל האותיות שהוכנסו) במקרה הגרוע (כשאין התחלות משותפות).

    טעויות נפוצות

    • לשכוח את isEnd. בלעדיו, search("app") היה מחזיר בטעות true אחרי הכנסה של "apple" בלבד.
    • לגרום ל-search להחזיר true רק כי המסלול קיים. זה startsWith. search צריכה גם את isEnd.
    • לשמור את האות ב-node במקום על הקשת ולהתבלבל לגבי ה-root. ה-root ריק; האותיות הן המפתחות של children.

    להעמקה

    • עם אותיות קטנות בלבד, children יכול להיות מערך של 26 תאים במקום map: קצת יותר מהיר, יותר זיכרון.
    • tries מפעילים השלמה אוטומטית, בודקי איות וטבלאות ניתוב IP. תשתמשו בו שוב ב-Design Add and Search Words וב-Word Search II.

    פתרון לדוגמה

    js
    class TrieNode {
      children = new Map() // letter → next node
      isEnd = false // does a whole word end at this node?
    }
    
    export default class Trie {
      root = new TrieNode() // the root holds no letter
    
      /**
       * @param {string} word
       * @return {void}
       */
      insert(word) {
        let node = this.root
        for (const char of word) {
          // Follow the letter, creating the node if this path doesn't exist yet.
          if (!node.children.has(char)) node.children.set(char, new TrieNode())
          node = node.children.get(char)
        }
        node.isEnd = true // mark that a word ends here
      }
    
      /**
       * @param {string} word
       * @return {boolean}
       */
      search(word) {
        // The path must exist AND a word must end exactly there.
        return this.#walk(word)?.isEnd ?? false
      }
    
      /**
       * @param {string} prefix
       * @return {boolean}
       */
      startsWith(prefix) {
        // Just reaching the end of the prefix is enough.
        return this.#walk(prefix) !== null
      }
    
      // Follow the letters from the root. Returns the last node, or null if a letter is missing.
      #walk(text) {
        let node = this.root
        for (const char of text) {
          node = node.children.get(char)
          if (!node) return null
        }
        return node
      }
    }
    ts
    class TrieNode {
      children = new Map<string, TrieNode>() // letter → next node
      isEnd = false // does a whole word end at this node?
    }
    
    export default class Trie {
      private root = new TrieNode() // the root holds no letter
    
      insert(word: string): void {
        let node = this.root
        for (const char of word) {
          // Follow the letter, creating the node if this path doesn't exist yet.
          let child = node.children.get(char)
          if (!child) {
            child = new TrieNode()
            node.children.set(char, child)
          }
          node = child
        }
        node.isEnd = true // mark that a word ends here
      }
    
      search(word: string): boolean {
        // The path must exist AND a word must end exactly there.
        return this.walk(word)?.isEnd ?? false
      }
    
      startsWith(prefix: string): boolean {
        // Just reaching the end of the prefix is enough.
        return this.walk(prefix) !== null
      }
    
      // Follow the letters from the root. Returns the last node, or null if a letter is missing.
      private walk(text: string): TrieNode | null {
        let node: TrieNode | undefined = this.root
        for (const char of text) {
          node = node.children.get(char)
          if (!node) return null
        }
        return node
      }
    }
    python
    class TrieNode:
        def __init__(self):
            self.children: dict[str, TrieNode] = {}  # letter → next node
            self.is_end = False  # does a whole word end at this node?
    
    
    class Trie:
        def __init__(self):
            self.root = TrieNode()  # the root holds no letter
    
        def insert(self, word: str) -> None:
            node = self.root
            for char in word:
                # Follow the letter, creating the node if this path doesn't exist yet.
                node = node.children.setdefault(char, TrieNode())
            node.is_end = True  # mark that a word ends here
    
        def search(self, word: str) -> bool:
            # The path must exist AND a word must end exactly there.
            node = self._walk(word)
            return node is not None and node.is_end
    
        def starts_with(self, prefix: str) -> bool:
            # Just reaching the end of the prefix is enough.
            return self._walk(prefix) is not None
    
        # Follow the letters from the root. Returns the last node, or None if a letter is missing.
        def _walk(self, text: str) -> TrieNode | None:
            node = self.root
            for char in text:
                node = node.children.get(char)
                if node is None:
                    return None
            return node