Discussion about this post

User's avatar
Tushar's avatar

Creating a directed graph and doing a topological sort should do the trick? With added logic to catch multiple sequences and unconnected sub graphs

Also when we do khans we can use backtracking to get all valid sequences

Vivek Sonar's avatar

from collections import defaultdict, deque

def reconstruct(subsequences):

chars = set("".join(subsequences))

g = defaultdict(set)

indeg = {c: 0 for c in chars}

for s in subsequences:

for a, b in zip(s, s[1:]):

if b not in g[a]:

g[a].add(b)

indeg[b] += 1

q = deque([c for c in chars if indeg[c] == 0])

res = []

while q:

if len(q) > 1:

return None

u = q.popleft()

res.append(u)

for v in g[u]:

indeg[v] -= 1

if indeg[v] == 0:

q.append(v)

return "".join(res) if len(res) == len(chars) else None

print(reconstruct(["ae","dcfe","ad"]))

print(reconstruct(["ab","bc"]))

print(reconstruct(["ae","dcf","de"]))

print(reconstruct(["ab","ac"]))

No posts

Ready for more?