Satisfiability of Equality Equations
Description
Given an array equations of strings that represent relationships between variables, each string equations[i]
has length 4
and takes one of two different forms: "a==b"
or "a!=b"
. Here, a
and b
are lowercase letters (not necessarily different) that represent one-letter variable names.
Return true
if and only if it is possible to assign integers to variable names so as to satisfy all the given equations.
Example 1:
Input: ["a==b","b!=a"] Output: false Explanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second. There is no way to assign the variables to satisfy both equations.
Example 2:
Input: ["b==a","a==b"] Output: true Explanation: We could assign a = 1 and b = 1 to satisfy both equations.
Example 3:
Input: ["a==b","b==c","a==c"] Output: true
Example 4:
Input: ["a==b","b!=c","c==a"] Output: false
Example 5:
Input: ["c==c","b==d","x!=z"] Output: true
Note:
1 <= equations.length <= 500
equations[i].length == 4
equations[i][0]
andequations[i][3]
are lowercase lettersequations[i][1]
is either'='
or'!'
equations[i][2]
is'='
Solution(javascript)
/** Union Find
* @param {string[]} equations
* @return {boolean}
*/
const equationsPossible = function (equations) {
const parent = {}
const size = {}
const notEquals = []
const root = (item) => {
while (parent[item] && item !== parent[item]) {
parent[item] = parent[parent[item]]
item = parent[item]
}
return item
}
const union = (a, b) => {
const rootA = root(a)
const rootB = root(b)
if (rootA === rootB) {
return
}
if (size[rootA] < size[rootB]) {
parent[rootA] = rootB
size[rootB] += size[rootA]
} else {
parent[rootB] = rootA
size[rootA] += size[rootB]
}
}
equations.forEach((item) => {
const var1 = item[0]
const var2 = item[3]
parent[var1] = parent[var1] || var1
parent[var2] = parent[var2] || var2
size[var1] = size[var1] || 1
size[var2] = size[var2] || 1
if (item[1] === '!') {
notEquals.push([var1, var2])
} else {
union(var1, var2)
}
})
return notEquals.every(([a, b]) => root(a) !== root(b))
}