Problem 558903 · medium · Phase 05 Advanced Algorithms & Graphs

Consistent Equality Rules

union-find · constraint satisfaction · string parsing

A puzzle gives a list rules, each a 4-character string of the form "x==y" or "x!=y" where x and y are lowercase letters. Each letter stands for an unknown integer. Return True if some assignment of integers to the letters satisfies every rule, and False otherwise.

Examples

Input:  rules = ["p==q", "q==r", "p!=r"]
Output: False
Explanation: p, q and r must all be equal, contradicting p != r.

Input:  rules = ["x==y", "y!=z"]
Output: True

Input:  rules = ["a!=a"]
Output: False

Constraints

  • 0 <= len(rules) <= 10**4, every rule is exactly 4 characters
  • Target: O(R * alpha(26)) time.

Goals

  • Process all equalities before checking any inequality
  • Detect contradictions with a single find per inequality
Starting Python…