Problem Description
Given an array of equations in the form "a==b" or "a!=b" where a and b are lowercase letters, determine if it’s possible to assign integers to variables such that all equations hold true.
Key Insights
- Process all equality equations first to group variables that must be equal.
- Use the Union Find (Disjoint Set Union) data structure to merge groups.
- After merging, check each inequality equation; if two variables known to be equal are required to be different, the equations are unsatisfiable.
- The limited range of variables (typically 26 letters) makes union-find operations efficient.
Space and Time Complexity
Time Complexity: O(n * α(n)) where n is the number of equations and α is the inverse Ackermann function (nearly constant). Space Complexity: O(1) since the number of distinct variables is constant (26).
Solution
We use a Union Find data structure to manage the equivalence between variables. The solution works in two phases:
- First pass: Iterate through the equations and perform union operations for every "==" equation, grouping variables that are equal.
- Second pass: Iterate through the equations again and for every "!=" equation, check if the two variables belong to the same group. If they do, return false as the equations contradict; otherwise, continue. If no contradiction is found, return true.
The key is processing all equalities first, so that when checking inequalities, the grouping is already established correctly.