String
Easy
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order
. The order
of the alphabet is some permutation of lowercase letters.
Given a sequence of words
written in the alien language, and the order
of the alphabet, return true
if and only if the given words are sorted lexicographically in this alien language.
Example 1
Example 2
Example 2
Let N
be the length of order
, and M
be the total number of characters in words
.
Time complexity : O(M)
Storing the letter-order
relation of each letter takes O(N)
time. For the nested for-loops, we examine each pair of words in the outer-loop and for the inner loop, we check each letter in the current word. Therefore, we will iterate over all of letters in words.
Taking both into consideration, the time complexity is O(M+N)
. However, we know that N
is fixed as 26
. Therefore, the time complexity is O(M)
.
Space complexity : O(1)
The only extra data structure we use is the hashmap/array that serves to store the letter-order
relations for each word in order
. Because the length of order is fixed as 26
, this approach achieves constant space complexity.
i < words.length - 1
?indexOf
actually increase time complexity?O(m+n)
?Question: why time complexity is O(s)
, which s stands for the sum of each word.length?
Solution 1: use hash map to store the order
Solution 2: use string.indexOf