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

Alien Dictionary

קשהgraphstopological sort

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

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

שפה חייזרית משתמשת באותיות אנגליות קטנות, אבל בסדר לא ידוע. נתונה לכם רשימת מילים words מהמילון שלה, ממוינת לפי האלפבית החייזרי.

החזירו מחרוזת של כל האותיות שמופיעות במילים, בסדר שמתאים למיון. אם כמה סדרים עובדים, החזירו כל אחד מהם. אם המילים סותרות זו את זו, כך שאף סדר לא עובד, החזירו "".

הבנת הבעיה

  • תחשבו על מילון רגיל: "apple" בא לפני "apply" כי, במיקום הראשון שבו הן שונות, e בא לפני y. המילון החייזרי עובד באותה דרך, אבל אתם לא מכירים את האלפבית שלו. צריך להסיק אותו מהמילים הממוינות.
  • רק המיקום הראשון שבו שתי מילים סמוכות שונות אומר משהו.
  • אם מילה אחת היא ההתחלה של השנייה (תחילית), הקצרה חייבת לבוא קודם: "ab" לפני "abc". אם הארוכה באה קודם, הקלט בלתי אפשרי.
  • אותיות בלי שום רמז יכולות להיות בכל מקום, אבל הן עדיין חייבות להופיע בתשובה שלכם.

דוגמה 1

text
Input:  words = ["wrt", "wrf", "er", "ett", "rftt"]
Output: "wertf"

מזוגות סמוכים: t לפני f, w לפני e, r לפני t, e לפני r. משרשרים אותם: w, e, r, t, f.

דוגמה 2

text
Input:  words = ["z", "x", "z"]
Output: ""

z לפני x, ואז x לפני z. בלתי אפשרי.

דוגמה 3

text
Input:  words = ["abc", "ab"]
Output: ""

"ab" היא תחילית של "abc", אז היא הייתה צריכה לבוא קודם.

אילוצים

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100

רמזים

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

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

    משווים כל זוג מילים סמוכות כדי ללמוד חוקים של "אות A באה לפני אות B", ואז מסדרים את כל האותיות כך שכל חוק נשמר (topological sort), ומחזירים "" אם החוקים סותרים זה את זה.

    שלב 1: הופכים את המילים הממוינות לחוקים

    רק מילים סמוכות נותנות מידע, ורק בהבדל הראשון שלהן:

    זוגההבדל הראשוןחוק
    "wrt" / "wrf"t / ft לפני f
    "wrf" / "er"w / ew לפני e
    "er" / "ett"r / tr לפני t
    "ett" / "rftt"e / re לפני r

    אותיות אחרי ההבדל הראשון לא אומרות כלום: ב-"wrf" מול "er", ה-r-ים באותו מיקום, אבל המילים כבר הוכרעו על ידי w מול e.

    מלכודת התחילית: אם שתי המילים תואמות עד סוף הקצרה מביניהן, אין חוק. אבל אם הארוכה באה קודם (כמו "abc" ואז "ab"), המילון לא תקין: מחזירים "" מיד.

    שלב 2: זו Course Schedule

    הופכים כל אות ל-node וכל חוק לחץ:

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

    אלפבית תקין הוא סדר של האותיות שבו כל חץ מצביע קדימה. זה topological sort, בדיוק כמו סידור קורסים לפי דרישות הקדם שלהם. משתמשים באותה שיטת in-degree (האלגוריתם של Kahn):

    1. נותנים לכל אות שמופיעה במילה כלשהי in-degree (כמה חוקים אומרים שמשהו בא לפניה). כוללים אותיות בלי חוקים, עם in-degree 0.
    2. מתחילים תור עם כל האותיות עם in-degree 0.
    3. שוב ושוב לוקחים אות, מוסיפים אותה לתשובה, ומורידים את ה-in-degree של כל אות שהיא מצביעה עליה. כל מי שמגיעה ל-0 מצטרפת לתור.
    4. אם בתשובה יש כל אות, מחזירים אותה. אם חסרות כמה, הן תקועות במעגל (כמו z → x → z): מחזירים "".

    לא לספור חוק פעמיים: אותו חוק יכול להופיע מכמה זוגות מילים. שומרים את העוקבות של כל אות ב-set, ומעלים את ה-in-degree רק כשהחוק חדש.

    צעד אחר צעד

    דוגמה 1. in-degrees: w 0, e 1, r 1, t 1, f 1. תור: [w].

    לוקחיםהתשובה עד עכשיופותחהתור אחרי
    wwe: 1 → 0 ✅[e]
    ewer: 1 → 0 ✅[r]
    rwert: 1 → 0 ✅[t]
    twertf: 1 → 0 ✅[f]
    fwertfכלום[]

    כל 5 האותיות מוקמו: "wertf".

    הקוד

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

    כמה זה מהיר?

    כש-C = מספר התווים הכולל בכל המילים:

    • זמן: O(C). איסוף אותיות והשוואת מילים סמוכות קוראים כל תו בערך פעם אחת. ה-topological sort זעיר: לכל היותר 26 אותיות.
    • זיכרון: O(1) בפועל: לכל היותר 26 אותיות ו-26 × 26 חוקים.

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

    • להשוות כל זוג מילים, לא רק סמוכות. סמוכות מספיקות, והן מה שהמיון מבטיח.
    • לקרוא אחרי ההבדל הראשון. רק האות הראשונה שונה היא חוק.
    • לשכוח את מקרה התחילית (["abc", "ab"] ← "").
    • להשמיט אותיות בלי חוקים. כל אות שמופיעה חייבת להיות בתשובה.
    • להוסיף את אותו חוק פעמיים ולנפח in-degree, כך שאות אף פעם לא מגיעה ל-0.

    להעמקה

    topological sort מופיע בכל פעם שדברים חייבים לקרות בסדר עם תלויות: מערכות build שמקמפלות קבצים, מנהלי חבילות שמתקינים ספריות, גיליונות אלקטרוניים שמחשבים מחדש תאים. קיימת גם גרסת DFS: מוסיפים אות לסדר אחרי שכל האותיות שהיא מצביעה עליהן סיימו, ואז הופכים.

    פתרון לדוגמה

    js
    /**
     * @param {string[]} words
     * @return {string}
     */
    export default function alienOrder(words) {
      // Graph of letters: successors.get(a) = letters that come after a.
      // inDegree.get(b) = how many letters must come before b.
      const successors = new Map()
      const inDegree = new Map()
      // Every letter that appears is a node, even letters with no rules.
      for (const word of words) {
        for (const char of word) {
          if (!successors.has(char)) {
            successors.set(char, new Set())
            inDegree.set(char, 0)
          }
        }
      }
    
      // Each pair of NEIGHBORING words gives at most one rule, at their first difference.
      for (let i = 0; i + 1 < words.length; i++) {
        const first = words[i]
        const second = words[i + 1]
        const length = Math.min(first.length, second.length)
        let j = 0
        while (j < length && first[j] === second[j]) j++
        if (j === length) {
          // No difference: a longer word before its own prefix is impossible.
          if (first.length > second.length) return ''
          continue
        }
        const before = successors.get(first[j])
        // Rule: first[j] comes before second[j]. Count it only once.
        if (!before.has(second[j])) {
          before.add(second[j])
          inDegree.set(second[j], inDegree.get(second[j]) + 1)
        }
      }
    
      // Topological sort (as in Course Schedule): start with letters nothing comes before.
      const queue = [...inDegree.keys()].filter((char) => inDegree.get(char) === 0)
      for (let i = 0; i < queue.length; i++) {
        for (const next of successors.get(queue[i])) {
          inDegree.set(next, inDegree.get(next) - 1)
          if (inDegree.get(next) === 0) queue.push(next) // everything before it is placed
        }
      }
      // Letters left out are stuck in a cycle: the rules contradict each other.
      return queue.length === inDegree.size ? queue.join('') : ''
    }
    ts
    export default function alienOrder(words: string[]): string {
      // Graph of letters: successors.get(a) = letters that come after a.
      // inDegree.get(b) = how many letters must come before b.
      const successors = new Map<string, Set<string>>()
      const inDegree = new Map<string, number>()
      // Every letter that appears is a node, even letters with no rules.
      for (const word of words) {
        for (const char of word) {
          if (!successors.has(char)) {
            successors.set(char, new Set())
            inDegree.set(char, 0)
          }
        }
      }
    
      // Each pair of NEIGHBORING words gives at most one rule, at their first difference.
      for (let i = 0; i + 1 < words.length; i++) {
        const first = words[i]
        const second = words[i + 1]
        const length = Math.min(first.length, second.length)
        let j = 0
        while (j < length && first[j] === second[j]) j++
        if (j === length) {
          // No difference: a longer word before its own prefix is impossible.
          if (first.length > second.length) return ''
          continue
        }
        const before = successors.get(first[j])!
        // Rule: first[j] comes before second[j]. Count it only once.
        if (!before.has(second[j])) {
          before.add(second[j])
          inDegree.set(second[j], inDegree.get(second[j])! + 1)
        }
      }
    
      // Topological sort (as in Course Schedule): start with letters nothing comes before.
      const queue = [...inDegree.keys()].filter((char) => inDegree.get(char) === 0)
      for (let i = 0; i < queue.length; i++) {
        for (const next of successors.get(queue[i])!) {
          inDegree.set(next, inDegree.get(next)! - 1)
          if (inDegree.get(next) === 0) queue.push(next) // everything before it is placed
        }
      }
      // Letters left out are stuck in a cycle: the rules contradict each other.
      return queue.length === inDegree.size ? queue.join('') : ''
    }
    python
    from collections import deque
    
    
    def alien_order(words: list[str]) -> str:
        # Graph of letters: successors[a] = letters that come after a.
        # in_degree[b] = how many letters must come before b. Every letter that appears is a node.
        successors = {char: set() for word in words for char in word}
        in_degree = {char: 0 for char in successors}
    
        # Each pair of NEIGHBORING words gives at most one rule, at their first difference.
        for first, second in zip(words, words[1:]):
            for a, b in zip(first, second):
                if a != b:
                    # Rule: a comes before b. Count it only once.
                    if b not in successors[a]:
                        successors[a].add(b)
                        in_degree[b] += 1
                    break
            else:
                # No difference (the loop never hit break): a longer word before its own prefix is impossible.
                if len(first) > len(second):
                    return ""
    
        # Topological sort (as in Course Schedule): start with letters nothing comes before.
        queue = deque(char for char, degree in in_degree.items() if degree == 0)
        order = []
        while queue:
            char = queue.popleft()
            order.append(char)
            for nxt in successors[char]:
                in_degree[nxt] -= 1
                if in_degree[nxt] == 0:  # everything before it is placed
                    queue.append(nxt)
        # Letters left out are stuck in a cycle: the rules contradict each other.
        return "".join(order) if len(order) == len(in_degree) else ""