Online store~35 min2s · 256 MBtarget O(n × L + 26^2 × 26^2) time, O(26^2) spaceclassic twin: lc-269topological-sort
A shop sorts its product codes on the shelf by a letter order of its own, and the order was lost. A list of codes remains, and it is supposed to be sorted by that order, with a code that starts another coming first.
An audit reads the list from the top. It wants the first code after which no letter order could possibly have sorted the codes read so far. That code is where the list was edited by mistake.
Write first_conflict(codes).
codes is a list of codes of lowercase letters. A letter order sorts the list when every code is not after the code that follows it.i such that no letter order sorts codes[0..i].-1 when some letter order sorts the whole list.Input: codes = ["ba", "bc", "ac", "ab"]
Output: 3The solution reads one rule from each pair of neighbouring codes, and keeps every rule that follows from them. A rule that contradicts a known one is the first conflict.
| Code | Rule from the pair before it | Table after the rule | Conflict |
|---|---|---|---|
0: ba |
none | empty | no |
1: bc |
a before c |
a before c | no |
2: ac |
b before a |
b before a, b before c | no |
3: ab |
c before b |
b already comes before c |
yes |
The rules a before c, b before a and c before b form a loop, so code 3 is the first conflict.
Input: codes = ["abc", "ab"]
Output: 1ab is the start of abc but comes after it, which no letter order can allow, so code 1 is the first conflict.
Input: codes = ["zx", "zy", "xz"]
Output: -1The rules are x before y and z before x, and the order z, x, y follows them, so no conflict exists.
1 ≤ len(codes) ≤ 20,0001 ≤ len(codes[i]) ≤ 8, and every code uses lowercase letters onlyRe-checking every prefix from scratch costs about 20,000 checks of up to 20,000 pairs each, which is 200,000,000 pairs. But there are only 26 letters, so at most 650 different rules exist. A table of 26 by 26 cells that grows as rules arrive keeps the work to one pass over the codes.