bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 269. Alien Dictionary

269. Alien Dictionary

Leetcode Solutions

Topological Sort using Depth-First Search (DFS)

  1. Initialize an adjacency list to represent the graph and a set to keep track of all unique characters.
  2. Compare each pair of adjacent words to determine the ordering of characters and build the graph.
  3. For each pair of adjacent words, find the first character that differs and create a directed edge from the first character to the second in the adjacency list.
  4. Initialize a color map to keep track of the state of each node during DFS (WHITE for unvisited, GRAY for visiting, BLACK for visited).
  5. Perform DFS on each unvisited node. If a cycle is detected (a GRAY node is encountered), return an empty string.
  6. During DFS, once a node's children are fully explored, add the node to the topological order.
  7. After DFS is complete, if all nodes are visited without detecting a cycle, return the characters in reverse order of their addition to the topological order.
  8. If not all characters are visited, it means there are isolated nodes, which should be added to the order as well.
UML Thumbnail

Topological Sort using Kahn's Algorithm

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...