A language uses the same 26 lowercase letters as English but in a different order. alphabet is a string of length 26 listing the letters from smallest to largest.
Sort words lexicographically according to that alphabet and return the sorted list. Comparison is letter by letter; if one word is a prefix of the other, the shorter word comes first. Identical words keep their original relative order.
Examples
Input: words = ["tone", "toes", "note"], alphabet = "notesabcdfghijklmpqruvwxyz"
Output: ["note", "tone", "toes"]
Explanation: 'n' is the smallest letter in this alphabet, so "note" comes first; 'n' precedes 'e', so "tone" < "toes".
Input: words = ["grandson", "grand"], alphabet = "abcdefghijklmnopqrstuvwxyz"
Output: ["grand", "grandson"]
Constraints
0 <= len(words) <= 5 * 10**4,1 <= len(words[i]) <= 20, lowercase letters onlyalphabetis a permutation of"abcdefghijklmnopqrstuvwxyz"- Target complexity: O(L log n) where
Lis the total number of letters.
Goals
- Translate letters into ranks using a lookup table
- Sort strings by a tuple of ranks so prefixes come first
- Keep equal words in their original order