Last active
September 26, 2022 22:35
-
-
Save dluciano/23d3a2b3366044321bb9c5df04ec3c42 to your computer and use it in GitHub Desktop.
990. Satisfiability of Equality Equations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public bool EquationsPossible(string[] equations) { | |
var uf = new UnionFind(26); | |
static (int x, int y, bool isEqual) Parse(in string equation) => | |
(equation[0] - 'a', equation[3] - 'a', equation[1] == '='); | |
foreach(var equation in equations){ | |
var (x, y, isEqual) = Parse(equation); | |
if(!isEqual) | |
continue; | |
if(x == y && !isEqual) | |
return false; | |
uf.Union(x, y); | |
} | |
foreach(var equation in equations){ | |
var (x, y, isEqual) = Parse(equation); | |
if(!isEqual && uf.IsConnected(x, y)) | |
return false; | |
} | |
return true; | |
} | |
private ref struct UnionFind { | |
private readonly int[] _parents; | |
private readonly int[] _ranks; | |
public UnionFind(int size){ | |
_parents = new int[size]; | |
_ranks = new int[size]; | |
for(var i = 0; i < size; i++){ | |
_parents[i] = i; | |
_ranks[i] = 1; | |
} | |
} | |
public int Find(int val){ | |
if(_parents[val] == val) | |
return val; | |
return _parents[val] = Find(_parents[val]); | |
} | |
public void Union(int a, int b){ | |
if(IsConnected(a, b, out var parentA, out var parentB)) | |
return; | |
if(_ranks[parentA] > _ranks[parentB]) | |
_parents[parentB] = parentA; | |
else if(_ranks[parentA] < _ranks[parentB]) | |
_parents[parentA] = parentB; | |
else{ | |
_parents[parentB] = parentA; | |
_ranks[parentA]++; | |
} | |
return; | |
} | |
public bool IsConnected(int a, int b) | |
=> IsConnected(a, b, out var _, out var _); | |
private bool IsConnected(int a, int b, out int parentA, out int parentB){ | |
parentA = Find(a); | |
parentB = Find(b); | |
return parentA == parentB; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment