Engineering platform~30 min2s · 256 MBtarget O(m log m × α(m)) time, O(m) spaceclassic twin: lc-990union-find
A config linter reads a spec made of rules, one per line. A rule says that two settings must be equal, written a==b, or different, written a!=b. A setting is named by lowercase letters.
The linter reads the rules from the top. It wants the first rule after which no choice of values for the settings can satisfy all the rules read so far. That rule is where the spec was broken.
Write first_contradiction(rules).
rules[i] is name==name or name!=name, where each name is one to six lowercase letters. A name may appear in many rules.x==y needs the same value for x and y. A rule x!=y needs different values. Any number of different values may be used.i such that no values satisfy rules[0..i].-1 when some values satisfy all the rules.Input: rules = ["a==b", "c!=d", "b==c", "d==a"]
Output: 3The solution groups names that must be equal. A group of equal names is a union-find set. The rules contradict when a different rule has both names in one group.
| Rule read | Groups of equal names | Different rules | Contradiction |
|---|---|---|---|
0: a==b |
a, b |
none | no |
1: c!=d |
a, b, c, d |
c and d |
no |
2: b==c |
a, b, c, d |
c and d |
no |
3: d==a |
a, b, c, d |
c and d |
yes: c and d are in one group |
Rule 3 joins d to the group of c, which the rule c!=d forbids, so the answer is 3.
Input: rules = ["a!=a"]
Output: 0A setting cannot differ from itself, so the first rule already contradicts.
Input: rules = ["a==b", "b!=c", "c==d"]
Output: -1The names a, b give one group and c, d another. The groups can have different values, so nothing contradicts.
1 ≤ len(rules) ≤ 100,000name==name or name!=name, with names of 1 to 6 lowercase lettersChecking every prefix from scratch takes about 5,000,000,000 rule visits in total. A check of one prefix takes one pass over its rules. Since contradictions only appear and never go away, a binary search needs about 17 checks, which is 1,700,000 visits.