An alien language writes with the 26 lower-case English letters, but ranks them differently. You get that ranking as order, a string holding every letter once, first-ranked letter first.
You also get a list of words. Return true if they appear in dictionary order under the alien ranking, and false otherwise. Two words are compared at their first differing letter; if one word runs out first (it is a prefix of the other), the shorter word comes first.
Example 1
Input: words = ["bed","bad","ace"], order = "bedacfghijklmnopqrstuvwxyz" Output: true Why: e ranks before a, and b before a
2 more examples and the constraints
Example 2
Input: words = ["cab","cat"], order = "tbacdefghijklmnopqrsuvwxyz" Output: false Why: they first differ at b and t; t ranks first
Example 3
Input: words = ["moon","mo"], order = "abcdefghijklmnopqrstuvwxyz" Output: false Why: "mo" is a prefix of "moon" so it must come first
Constraints
- 1 ≤ number of words ≤ 100
- 1 ≤ length of each word ≤ 20
- order has length 26 and holds each lower-case letter once
- words use lower-case letters only
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Translate to plain lettersO(C)
- Rank table, compare neighboursO(C)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Letters touched for 100 words of 20 letters | Verdict |
|---|---|---|---|
| Translate to plain letters | O(C) | Passes; rewrites every word | |
| Rank table, compare neighbours | O(C) | Best; stops at the first difference |
C = total number of letters in words. Both are linear; the rank version reads less and copies nothing.
Edge cases to test
- One word. There are no pairs, so the answer is true.
- Equal neighbours. "aa" then "aa" is sorted: equal words are allowed.
- Prefix order. "mo" before "moon" is fine; "moon" before "mo" is not.
- Late mistake. The first pairs can all be fine; one bad pair anywhere makes the answer false.
Common mistakes
- Comparing letters with the normal alphabet (
x < y) instead of their alien ranks. - Forgetting the prefix case and returning true for "moon" before "mo".
- Checking every position of the pair instead of stopping at the first difference, which lets a later letter overrule it.
How to talk through it
- 1Clarify. Are equal neighbours allowed? Does a shorter prefix come first, as in a normal dictionary?
- 2Reduce to pairs. Sorted order is transitive, so checking each neighbouring pair is enough.
- 3Rank the letters. A 26-entry table gives each letter's position in O(1).
- 4Compare a pair. The first differing letter decides; with no difference, the shorter word must come first. O(C) time, O(1) space.
- 5Test out loud. Run one word, a prefix pair in both orders, and a list whose only mistake is the last pair.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?