Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Checking validity of equations in JavaScript
In JavaScript, we need to check if a set of variable equations can all be satisfied simultaneously. This involves parsing equality and inequality constraints and determining if consistent variable assignments exist.
Problem Statement
Given an array of string equations in the format 'X===Y' (equality) or 'X!==Y' (inequality), determine if we can assign values to variables such that all equations evaluate to true.
Understanding the Logic
The solution uses a Union-Find (Disjoint Set) data structure:
- Group equal variables into the same set
- Check if any inequality constraint violates the grouping
- If variables that must be unequal are in the same group, return false
Example with Contradiction
const arr = ['X===Y', 'Y!==Z', 'X===Z'];
const validateEquations = (arr = []) => {
const map = {};
const len = {};
const inValids = [];
// Find root of set with path compression
const find = (item) => {
while(map[item] && item !== map[item]){
map[item] = map[map[item]];
item = map[item];
};
return item;
};
// Union two sets by rank
const add = (a, b) => {
const first = find(a);
const second = find(b);
if(first === second){
return;
};
if(len[first] < len[second]){
map[first] = second;
len[second] += len[first];
}else{
map[second] = first;
len[first] += len[second];
}
}
// Process each equation
arr.forEach((item) => {
const X = item[0];
const Y = item[4];
map[X] = map[X] || X;
map[Y] = map[Y] || Y;
len[X] = len[X] || 1;
len[Y] = len[Y] || 1;
if(item[1] === '!'){
inValids.push([X, Y]);
}else{
add(X, Y);
};
});
// Check if any inequality constraint is violated
return inValids.every(([a, b]) => find(a) !== find(b))
};
console.log(validateEquations(arr));
false
Example with Valid Equations
const validArr = ['A===B', 'B===C', 'X!==Y']; console.log(validateEquations(validArr));
true
How the Algorithm Works
For the input ['X===Y', 'Y!==Z', 'X===Z']:
- Process 'X===Y': Group X and Y together
- Process 'Y!==Z': Store as inequality constraint
- Process 'X===Z': Group X and Z together (Z joins X,Y group)
- Check inequality 'Y!==Z': Both Y and Z are in same group ? Contradiction!
Key Points
- Uses Union-Find for efficient grouping of equal variables
- Path compression optimizes find operations
- Union by rank maintains balanced tree structure
- Returns false if any inequality constraint is violated
Conclusion
This solution efficiently determines equation validity using Union-Find data structure. It groups equal variables and checks for contradictions with inequality constraints.
Advertisements
