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']:

  1. Process 'X===Y': Group X and Y together
  2. Process 'Y!==Z': Store as inequality constraint
  3. Process 'X===Z': Group X and Z together (Z joins X,Y group)
  4. 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.

Updated on: 2026-03-15T23:19:00+05:30

346 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements