Check for Contradictions in Equations - Problem

You are given a 2D array of strings equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] means that Ai / Bi = values[i].

Determine if there exists a contradiction in the equations. Return true if there is a contradiction, or false otherwise.

Note: When checking if two numbers are equal, check that their absolute difference is less than 10^-5. The testcases are generated such that there are no cases targeting precision, i.e. using double is enough to solve the problem.

Input & Output

Example 1 — No Contradiction
$ Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0]
Output: false
💡 Note: We have a/b = 2.0 and b/c = 3.0, which gives a/c = 6.0. No contradictory equations exist.
Example 2 — Direct Contradiction
$ Input: equations = [["a","b"],["a","b"]], values = [2.0,3.0]
Output: true
💡 Note: Same equation a/b appears twice with different values (2.0 and 3.0), which is a contradiction.
Example 3 — Indirect Contradiction
$ Input: equations = [["a","b"],["b","c"],["a","c"]], values = [2.0,3.0,5.0]
Output: true
💡 Note: We have a/b = 2.0 and b/c = 3.0, so a/c should be 6.0, but the direct equation gives a/c = 5.0.

Constraints

  • 1 ≤ equations.length ≤ 500
  • equations[i].length == 2
  • 1 ≤ equations[i][j].length ≤ 5
  • values[i] > 0.0
  • 1 ≤ values.length ≤ 500

Visualization

Tap to expand
Check for Contradictions in EquationsInput Equations[["a","b"],["b","c"]][2.0, 3.0]Build Grapha/b = 2.0b/c = 3.0Check Pathsa/c = a/b × b/c= 2.0 × 3.0 = 6.0abc2.03.0Result: false (No contradiction found)
Understanding the Visualization
1
Input
Equations define ratios between variables
2
Process
Build graph and check for contradictory paths
3
Output
Return true if contradiction found, false otherwise
Key Takeaway
🎯 Key Insight: Model equations as a weighted graph and detect contradictory paths using graph traversal algorithms
Asked in
Google 15 Facebook 12 Amazon 8
12.5K Views
Medium Frequency
~35 min Avg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen