Medium
Strings Differ by One Character — C++
Full explanation · Time O(n * m) · Space O(n)
// Time: O(n * m)
// Space: O(n)
class Solution {
public:
bool differByOne(vector<string>& dict) {
static const int MOD = 1e9 + 7;
static const int64_t P = 113;
vector<int> hashes(dict.size());
for (int i = 0; i < dict.size(); ++i) {
for (const auto& c : dict[i]) {
hashes[i] = (P * hashes[i] + (c - 'a')) % MOD;
}
}
int64_t base = 1;
for (int p = dict[0].length() - 1; p >= 0; --p) {
unordered_map<int, vector<int>> lookup;
for (int i = 0; i < dict.size(); ++i) {
int new_hash = ((hashes[i] - base * (dict[i][p] - 'a') % MOD) + MOD) % MOD;
if (lookup.count(new_hash)) {
auto target = dict[i].substr(0, p);
target += dict[i].substr(p + 1);
for (const auto& j : lookup[new_hash]) {
auto candidate = dict[j].substr(0, p);
candidate += dict[j].substr(p + 1);
if (candidate == target) {
return true;
}
}
}
lookup[new_hash].emplace_back(i);
}
base = (P * base) % MOD;
}
return false;
}
};