29 · Topological Sort

#269 Alien Dictionary

frequently reported atUberAirbnbMetaAmazonGoogle

the problem

In plain words

You get a list of words sorted in an unknown alien alphabet (lowercase English letters). Return a string of all the letters that appear, in an order consistent with the list, or "" if no order fits. Any valid answer is accepted.

in words = ["wrt","wrf","er","ett","rftt"]

out "wertf"

t<f, w<e, r<t, e<r → w, e, r, t, f.

in words = ["z","x"]

out "zx"

in words = ["z","x","z"]

out ""

z<x and x<z — a cycle.

  • 1 ≤ words.length ≤ 100
  • 1 ≤ words[i].length ≤ 100
  • Lowercase English letters

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code right here. Stuck for 20 minutes? Open one hint at a time.

This one is LeetCode Premium. You don't need a subscription: solve it right here. The free alternative linked above is the closest free practice; its label says how close it is.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #953
    2. #210
      Course Schedule II
      Mediumin Topo Sort