HardArrayStringDepth-First SearchBreadth-First SearchGraphTopological Sort

Alien Dictionary

LeetCode
1 approach, code in all languages

You are given a list of words written in an alien language. Within this language the letters are drawn from the usual lowercase English alphabet, but their relative order is unknown.

The words are provided in an order that is lexicographically sorted according to the rules of this alien language. Using only that ordering information, determine a possible sequence of the distinct letters that appear, from smallest to largest.

Return any valid ordering as a string. If no consistent ordering exists, return an empty string. If several orderings are valid, returning any one of them is acceptable.

Example 1

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

Output: "wertf"

Comparing neighbors yields t before f, w before e, r before t, and e before r, which chains into the order w, e, r, t, f.

Example 2

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

Output: ""

A longer word appears before one of its own prefixes, which can never happen in a valid sorted list, so no ordering exists.

Constraints

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] consists of only lowercase English letters.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now