Chain Fragment Payloads by Matching Tags
Trees & GraphsModel answerLast updated
Order tagged fragments so each fragment's ending tag matches the next fragment's starting tag, then concatenate their payloads into a single output string.
You receive a collection of labeled fragments. Each fragment is represented as a triple:
start_tag: a string labelend_tag: a string labelpayload: a string of content
Fragments connect when one fragment's end_tag matches another fragment's start_tag. Your task is to order the fragments into a valid sequence and produce the concatenated payload string.
Part 1: Directed Single Path
The fragments form exactly one directed path. Each fragment's end_tag matches the start_tag of exactly one other fragment (except the last fragment). Assemble the fragments in order and return the concatenated payload.
Example:
Input fragments:
("START", "A1B", "First")
("A1B", "C2D", "Second")
("C2D", "E3F", "Third")
("E3F", "END", "Fourth")
Output:
"FirstSecondThirdFourth"
Part 2: Bidirectional Single Path
Now each fragment can be traversed in either direction. You may assemble the path forward or backward. Both directions produce valid answers.
- Forward: payloads concatenated in their natural order
- Backward: payloads concatenated in reverse order
Example (same fragments as Part 1):
Valid outputs:
"FirstSecondThirdFourth"(forward traversal)"FourthThirdSecondFirst"(backward traversal)
Part 3: Multiple Disjoint Paths
The input may contain fragments that form several separate paths. No path branches or merges. Return one concatenated string per path, in any order.
Output format:
- Part 1 & 2: a single string
- Part 3: a list of strings
Hints
Hint 1
Model each fragment as an edge in a graph where tags are nodes
Hint 2
In Part 1, find the unique starting node that has no incoming edge
Hint 3
In Part 2, path endpoints are nodes with degree 1; walk from either end
Hint 4
Track which fragments you've used by their index, not by their tags
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each part changes how fragments connect. Recognizing the graph structure early simplifies the solution.
Part 1 treats fragments as directed edges. Tags are nodes, and each fragment connects start_tag → end_tag. The input forms a single directed path, so there is exactly one node with no incoming edge—the head of the chain. Index all fragments by their start_tag, find the head, then follow end_tag pointers until you reach the tail.
Part 2 treats fragments as undirected edges. Each fragment connects two tags without imposing direction. A simple path has exactly two degree-1 nodes (the endpoints) and every other node has degree 2. Start at any endpoint and repeatedly take the one unused edge at your current position. Append the payload and move to the tag at the other end. If you start from the opposite endpoint, you get payloads in reverse order. Both are correct.
Part 3 extends Part 2 to multiple disjoint paths. Run the Part 2 walk starting from every degree-1 node whose edges haven't been visited. Each walk consumes one entire connected component. For defensive handling of cycles (which the problem forbids), start a walk from any remaining unused edge.
Why This Works
-
Part 1: In a valid directed path, each tag is the
start_tagof at most one fragment. Exactly one fragment has no predecessor, making it the unique head. Following the chain visits every fragment once in the correct order. -
Part 2 & 3: In a path, endpoints have degree 1. From an endpoint, every interior node has exactly one unused edge—the one you didn't arrive on. The walk cannot branch and stops only at the other endpoint after visiting every edge in the component. Starting walks only from unused endpoints ensures each path is assembled exactly once.
Complexity
Let n be the number of fragments and L the total length of all payloads.
- Time: O(n + L). Building adjacency lists takes O(n). Each fragment is visited once. Concatenating payloads with
joincosts O(L). Avoid repeated string concatenation with+=, which can degrade to O(L²). - Space: O(n + L) for adjacency maps, usage flags, and output strings.
Edge Cases and Pitfalls
- Empty input: Part 1 & 2 return
"", Part 3 returns[]. - Single fragment: output is just its payload.
- Empty payloads: must still be included in the traversal so the walk continues correctly.
- Duplicate tag pairs or self-loops: track fragments by their index (edge ID), not by their tag pair.
- No valid head in Part 1: if zero or multiple heads exist, the input is invalid; raise an error rather than silently returning partial output.
- Cycles in Part 3: the fallback pass over unused edges handles them, starting at an arbitrary point in the cycle.
- Tag matching is exact: don't assume tags have fixed length or come from a specific alphabet.
Code
from collections import defaultdict
from typing import List, Tuple
Fragment = Tuple[str, str, str] # (start_tag, end_tag, payload)
# -------- Part 1: single directed path --------
def assemble_directed(fragments: List[Fragment]) -> str:
if not fragments:
return ""
by_start = {}
all_ends = set()
for start, end, payload in fragments:
if start in by_start:
raise ValueError(f"Multiple fragments start with {start!r}")
by_start[start] = (end, payload)
all_ends.add(end)
# Head is the start_tag that never appears as an end_tag
heads = [s for s in by_start if s not in all_ends]
if len(heads) != 1:
raise ValueError("Input does not form a single directed path")
parts = []
current = heads[0]
for _ in range(len(fragments)):
if current not in by_start:
break
next_tag, payload = by_start[current]
parts.append(payload)
current = next_tag
if len(parts) != len(fragments):
raise ValueError("Fragments do not form one connected path")
return "".join(parts)
# -------- Shared machinery for Part 2 & 3 --------
def find_all_paths(fragments: List[Fragment]) -> List[str]:
adjacency = defaultdict(list) # tag -> [(fragment_id, other_tag)]
for idx, (tag_a, tag_b, _) in enumerate(fragments):
adjacency[tag_a].append((idx, tag_b))
adjacency[tag_b].append((idx, tag_a))
visited = [False] * len(fragments)
def traverse_from(start_tag: str) -> str:
payloads = []
current = start_tag
while True:
next_step = next(
((fid, other) for fid, other in adjacency[current] if not visited[fid]),
None
)
if next_step is None:
return "".join(payloads)
frag_id, current = next_step
visited[frag_id] = True
payloads.append(fragments[frag_id][2])
paths = []
# Start from each degree-1 endpoint
for tag, neighbors in adjacency.items():
if len(neighbors) == 1 and not visited[neighbors[0][0]]:
paths.append(traverse_from(tag))
# Handle cycles (no degree-1 nodes)
for idx, (tag_a, _, _) in enumerate(fragments):
if not visited[idx]:
paths.append(traverse_from(tag_a))
return paths
# -------- Part 2: single path, either direction --------
def assemble_bidirectional(fragments: List[Fragment]) -> str:
paths = find_all_paths(fragments)
if not paths:
return ""
if len(paths) != 1:
raise ValueError("Fragments form multiple paths")
return paths[0]
# -------- Part 3: multiple paths --------
def assemble_multiple(fragments: List[Fragment]) -> List[str]:
return find_all_paths(fragments)
Example Usage
frags = [
("START", "A1B", "First"),
("A1B", "C2D", "Second"),
("C2D", "E3F", "Third"),
("E3F", "END", "Fourth")
]
print(assemble_directed(frags))
# Output: "FirstSecondThirdFourth"
print(assemble_bidirectional(frags))
# Output: "FirstSecondThirdFourth" or "FourthThirdSecondFirst"
multi = frags + [("X", "Y", "Alpha"), ("Y", "Z", "Beta")]
print(assemble_multiple(multi))
# Output: ["FirstSecondThirdFourth", "AlphaBeta"] (order may vary)