990. Satisfiability of Equality Equations

Question:

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] and equations[i][3] are lowercase letters
  • equations[i][1] is either ‘=’ or ‘!’
  • equations[i][2] is ‘=’

Solution:

  • Method 1: Union find set beats 100%
     class Solution {
          private static final char EQ = '=';
          private static final char NOT_EQ = '!';
          private char[] uf;
          public boolean equationsPossible(String[] equations) {
              this.uf = new char[26];
              for(int i = 0; i < 26; i++) uf[i] = (char)(i + 'a');
              for(int i = 0; i < equations.length; i++){
                  String eq = equations[i];
                  if(eq.charAt(1) == EQ){ // Add to union find set
                      union(eq.charAt(0), eq.charAt(3));
                  }
              }
              for(int i = 0; i < equations.length; i++){
                  String eq = equations[i];
                  if(eq.charAt(1) == NOT_EQ){
                      char a = find(eq.charAt(0));
                      char b = find(eq.charAt(3));
                      if(a == b) return false;
                  }
              }
              return true;
          }
          private char find(char c){
              if(c != uf[c - 'a']){
                  uf[c - 'a'] = find(uf[c - 'a']);
              }
              return uf[c - 'a'];
          }
          private void union(char a, char b){
              char p = find(a);
              char q = find(b);
              uf[p - 'a'] = q;
          }
      }