Engineering platform~25 min2s · 256 MBtarget O(L α(L)) time, O(R) spaceclassic twin: lc-990union-find
The engineering platform behind an app stores its settings in config files. A file is a list of rules in one line, separated by commas. A rule says that two settings are equal, written a==b, or different, written a!=b.
A file is consistent when some choice of values for its settings satisfies every rule in it. Each file stands alone: a setting named a in one file has nothing to do with a in another.
Write count_consistent_files(files).
files[i] is one file: rules joined by commas, such as "a==b,b!=c".name==name or name!=name, and a name is one or more lowercase letters.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.Input: files = ["a==b,b!=c,c==a", "a==b,b==c,a!=d", "x!=y,y!=z,x!=z"]
Output: 2The solution works on one file at a time. It joins the names of all equal rules into groups, and only then checks each different rule.
| File | Groups after the equal rules | Different rules | Consistent |
|---|---|---|---|
0: a==b,b!=c,c==a |
a, b, c |
b!=c: both in one group |
no |
1: a==b,b==c,a!=d |
a, b, c and d |
a!=d: apart |
yes |
2: x!=y,y!=z,x!=z |
x, y, z |
all apart | yes |
Two files are consistent. File 0 fails because c==a joins c to b after the rule b!=c.
Input: files = ["m!=m"]
Output: 0A setting cannot differ from itself.
Input: files = ["a==b", "a!=b"]
Output: 2The files do not share settings. Each is consistent by itself.
1 ≤ len(files) ≤ 2,0003 ≤ len(files[i]) ≤ 4,000, with the letters a to z and the symbols =, ! and ,A file can hold about 440 rules, and there can be 2,000 files, so the input has up to 8,000,000 characters. Each rule must be read a constant number of times. Sweeping over the rules until nothing changes can take 440 sweeps of 440 rules for one file.