Skip to main content

Alien Dictionary

Question

None

Example 1
Input: words = ["word","world","row"]
Output: "dlorw"

Solution

all//Alien Dictionary.py

# Alien Dictionary
#
# Create a function that takes in two strings, "words" and "order".
#
# Return true if the given words are in the correct order in the given alien dictionary, and false otherwise.

def alien_dictionary(words, order):

# Create a dictionary with keys from the order string and values as their indices
order_dict = {c: i for i, c in enumerate(order)}

# Iterate through each pair of words in the words list
for i in range(len(words)-1):
w1 = words[i]
w2 = words[i+1]

# Iterate through each character in the words
for j in range(min(len(w1), len(w2))):

# Check if the characters from the two words have different indices in the dictionary
if order_dict[w1[j]] < order_dict[w2[j]]:
break
elif order_dict[w1[j]] > order_dict[w2[j]]:
return False
else:
# If all characters are the same, and w1 is longer than w2, then it's not sorted correctly
if len(w1) > len(w2):
return False

# Return true if all words are sorted correctly
return True


words = ["word","world","row"]