oneby7

Graphs Union-find

469. Satisfiability of Equality Equations

Medium

You are given equations, a list of equations between variables. Every variable is a single lowercase letter. Each equation is a string of four characters, written either as "x==y", which says that x and y are equal, or as "x!=y", which says that they are different. Here x and y stand for any two letters, and they can be the same letter.

Return true if you can give each variable an integer value so that all the equations hold at the same time. Otherwise return false. A variable has one value in every equation it appears in. Two different variables may have the same value unless an equation says they differ.

Example 1

Input: equations = ["x==y", "z!=x", "y==z"]

Output: false

Explanation: x == y and y == z make x equal to z. But z != x needs them to be different, so no values work.

Example 2

Input: equations = ["u!=v", "v!=w", "w!=u", "w==t"]

Output: true

Explanation: Give u the value 1, v the value 2, and both w and t the value 3. Every equation holds.

Example 3

Input: equations = ["k!=k"]

Output: false

Explanation: A variable always equals itself, so k != k can never hold.

Check your understanding

Work out the answer for this input before you write any code.

equations = ["e!=f", "f!=g", "g!=e"]

Constraints

  • 1 ≤ equations.length ≤ 105
  • equations[i].length == 4
  • equations[i][0] and equations[i][3] are lowercase English letters.
  • equations[i][1] is '=' or '!', and equations[i][2] is '='.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.