KatInterview

Chain Fragment Payloads by Matching Tags

Trees & GraphsModel answer
MediumModel answerTrees & Graphsgraphsstring-manipulationgraph-traversal

Last 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 label
  • end_tag: a string label
  • payload: 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