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 Equations INPUT equations[] ["a","b"] ["b","c"] values[] 2.0 3.0 Graph Representation a b c 2.0 3.0 a/b=2, b/c=3 a=2b, b=3c so a=6c ALGORITHM STEPS 1 Build Graph Create adjacency list with edge weights from values[] 2 DFS Traversal Assign values to variables relative to starting node 3 Check Consistency If node visited, verify |computed - stored| < 10^-5 4 Detect Contradiction Return true if mismatch, false if all consistent DFS Assignment: a = 1.0 (start) b = 1.0/2.0 = 0.5 c = 0.5/3.0 = 0.167 FINAL RESULT Consistency Check a 1.0 b 0.5 c 0.167 a/b = 1.0/0.5 = 2.0 [OK] b/c = 0.5/0.167 = 3.0 [OK] Output: false No Contradiction All equations are consistent! Key Insight: Model equations as a weighted directed graph where a/b=k creates edges a-->b (weight k) and b-->a (weight 1/k). Use DFS to assign relative values. A contradiction exists if we reach a visited node with a different computed value. Tolerance of 10^-5 handles floating-point precision issues in comparisons. TutorialsPoint - Check for Contradictions in Equations | DFS Graph Traversal
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