Verifying an Alien Dictionary

Are the words sorted in the given alien order? Pairwise compare via rank map.

Easy
Time O(C) Space O(|Σ|)
LeetCode
4 min read
topological-sort string

Problem#

Given words and an alien order string, return true iff words is sorted according to that order.

Examples#

  • words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"true
  • words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"false

Constraints#

  • 1 <= words.length <= 100.

Approach#

Build rank[c] = position of c in order. For each adjacent word pair, compare character ranks at the first differing position; if no difference within shorter length, the shorter must precede.

Solution#

Verifying an Alien Dictionary
class Solution {
public:
bool isAlienSorted(vector<string>& words, string order) {
int rank[26];
for (int i = 0; i < 26; ++i) rank[order[i] - 'a'] = i;
for (int i = 0; i + 1 < (int)words.size(); ++i) {
const string& a = words[i];
const string& b = words[i + 1];
int n = min(a.size(), b.size()), j = 0;
for (; j < n && a[j] == b[j]; ++j) {}
if (j == n) {
if (a.size() > b.size()) return false;
} else if (rank[a[j] - 'a'] > rank[b[j] - 'a']) return false;
}
return true;
}
};

Editorial#

The rank-table inversion turns “is character X less than Y in alien order?” into a single int comparison. Edge case: identical prefixes mean the shorter word must come first.

Complexity#

  • Time: O(total chars).
  • Space: O(1) (26 ranks).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.