1. Exhaustive Permutation Verification
Intuition
Generate all permutations of unique alien letters and check if any permutation satisfies every adjacent word ordering constraint.
Algorithm
- Collect all unique characters from the dictionary words.
- Generate all permutations of these characters using backtracking.
- For each permutation, assign an integer rank to each character.
- Verify if
wordsis strictly sorted according to this rank assignment. - If sorted, return the candidate string.
- If all permutations fail, return empty string.
#include <iostream>#include <vector>#include <string>#include <unordered_set>#include <unordered_map>#include <algorithm> class Solution { bool isSorted(const std::vector<std::string>& words, const std::string& order) { std::unordered_map<char, int> rank; for (int i = 0; i < order.size(); ++i) rank[order[i]] = i; for (int i = 0; i + 1 < words.size(); ++i) { const std::string& w1 = words[i]; const std::string& w2 = words[i + 1]; int len = std::min(w1.size(), w2.size()); bool diff = false; for (int j = 0; j < len; ++j) { if (w1[j] != w2[j]) { if (rank[w1[j]] > rank[w2[j]]) return false; diff = true; break; } } if (!diff && w1.size() > w2.size()) return false; } return true; }public: std::string alienOrder(std::vector<std::string>& words) { std::unordered_set<char> charSet; for (const auto& w : words) { for (char c : w) charSet.insert(c); } std::string chars(charSet.begin(), charSet.end()); std::sort(chars.begin(), chars.end()); do { if (isSorted(words, chars)) return chars; } while (std::next_permutation(chars.begin(), chars.end())); return ""; }}; int main() { Solution sol; std::vector<std::string> words = {"z", "x"}; std::cout << "Alien order: " << sol.alienOrder(words) << " (Expected: zx)\n"; return 0;}Time & Space Complexity
- Time complexity:
O(U! * N * L) - Space complexity:
O(U)