990. Satisfiability of Equality Equations #
Problem #
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 <= 500equations[i].length == 4equations[i][0]andequations[i][3]are lowercase lettersequations[i][1]is either'='or'!'equations[i][2]is'='
Problem Summary #
Given an array of string equations representing relationships between variables, each string equation 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 only if it is possible to assign integers to variable names so that all the given equations are satisfied; otherwise return false.
Constraints:
- 1 <= equations.length <= 500
- equations[i].length == 4
- equations[i][0] and equations[i][3] are lowercase letters
- equations[i][1] is either ‘=’ or ‘!’
- equations[i][2] is ‘=’
Solution Approach #
- Given a string array, the array contains relationships between letters, with only two types of relationships:
'=='and'! ='. Determine whether there is a contradiction among these given relationships. - This is a simple union-find problem. First
union()all letters with'=='relationships, then check each'! ='relationship to see whether there is a combination that has a'=='relationship. If so, returnfalse; if none are found after traversal, returntrue.
Code #
package leetcode
import (
"github.com/halfrost/leetcode-go/template"
)
func equationsPossible(equations []string) bool {
if len(equations) == 0 {
return false
}
uf := template.UnionFind{}
uf.Init(26)
for _, equ := range equations {
if equ[1] == '=' && equ[2] == '=' {
uf.Union(int(equ[0]-'a'), int(equ[3]-'a'))
}
}
for _, equ := range equations {
if equ[1] == '!' && equ[2] == '=' {
if uf.Find(int(equ[0]-'a')) == uf.Find(int(equ[3]-'a')) {
return false
}
}
}
return true
}