Sequence Reconstruction solution explained
Sequence Reconstruction asks whether a proposed order of n labels is the only order that respects a set of shorter fragments, where each fragment fixes the relative order of the labels it contains. Turn the fragments into directed edges and run Kahn's topological sort: the order is unique exactly when the ready queue holds one label at every step and the labels come out in the proposed order. That check runs in O(n + total fragment length).
By Evin JohnPublished 9 min read
The problem in plain words
You are given a proposed order, a list of the labels 1 to n each used once, and some fragments. A fragment is a short list of distinct labels and means "these labels must appear in this relative order", without saying anything about labels between them. Decide whether the proposed order is the one and only arrangement of all n labels that agrees with every fragment. If another arrangement would also fit, or the proposed order breaks a fragment, the answer is false.
The well-known version phrases this as "is the order the unique shortest supersequence of the fragments" and promises that every fragment already agrees with the order. The two phrasings agree on all such inputs. The code here does not rely on that promise, so it also returns false when a fragment contradicts the order.
| Order and fragments | Answer | Why |
|---|---|---|
| [1,2,3,4] with [1,2,4], [2,3,4] | true | The edges 1→2, 2→3 and 3→4 pin every neighbouring pair, so nothing can move |
| [1,2,3] with [1,3], [2,3] | false | Both 1 and 2 must come before 3, but nothing orders 1 against 2, so [2,1,3] also fits |
| [3,1,2] with [3,1], [1,2] | true | A single chain 3, 1, 2 |
| [2,1,3,4] with [2,1], [1,4] | false | Label 3 appears in no fragment, so it could go anywhere |
| [2,1] with [1,2] | false | The order itself breaks the fragment |
| [1] with no fragments | true | One label has only one arrangement |
What the interviewer is checking
Most candidates know how to produce one topological order. This problem asks whether it is the only one, which tests whether you understand when Kahn's algorithm has freedom. The interviewer listens for the key observation: whenever two labels are ready at the same time, either could go next, so the order is not unique. They also watch for the details that sink many attempts: labels that appear in no fragment, fragments with a single label, and fragments that disagree with the proposed order.
Brute force: try every arrangement
For small n you can check the definition directly. Generate every permutation of the labels, keep the ones in which each fragment's labels appear in increasing positions, and answer true only if exactly one arrangement survives and it is the proposed order. There are n! permutations and each costs O(n + L) to test, so this is only a checker for n up to about 8.
from itertools import permutations
def is_only_order_slow(order, fragments):
n = len(order)
fits = []
for arrangement in permutations(range(1, n + 1)):
where = {label: i for i, label in enumerate(arrangement)}
if all(where[a] < where[b]
for frag in fragments for a, b in zip(frag, frag[1:])):
fits.append(list(arrangement))
if len(fits) > 1: # a second fit already means "not unique"
return False
return fits == [list(order)]Optimal: Kahn's algorithm with no choices allowed
Each fragment only constrains neighbours: if a comes right before b in a fragment, add an edge a → b. Longer-range constraints follow by chaining. Now run Kahn's algorithm. At every step, the labels with in-degree zero are exactly the ones that could go next. If there are two or more, the order has a choice, so it is not unique. If there is exactly one, it must match the next label of the proposed order. Finally, all n labels must come out. A cycle leaves some labels stuck and the count falls short.
def is_only_order(order, fragments):
n = len(order)
after = [set() for _ in range(n + 1)] # a set skips repeated edges
indeg = [0] * (n + 1)
for frag in fragments:
for a, b in zip(frag, frag[1:]):
if b not in after[a]:
after[a].add(b)
indeg[b] += 1
ready = [label for label in range(1, n + 1) if indeg[label] == 0]
placed = 0
while ready:
if len(ready) > 1: # two labels could go next
return False
label = ready.pop()
if label != order[placed]: # forced, but not what was proposed
return False
placed += 1
for nxt in after[label]:
indeg[nxt] -= 1
if indeg[nxt] == 0:
ready.append(nxt)
return placed == n # a cycle would stop us earlyUsing a set per label matters. Two fragments can both contain the pair 2 then 3. Counting that edge twice is harmless for the final result as long as it is also decremented twice, but storing it once keeps the counts honest and the loop simple. Since the ready list never holds more than one label when the loop continues, a plain list works as the queue.
function isOnlyOrder(order, fragments) {
const n = order.length;
const after = Array.from({ length: n + 1 }, () => new Set());
const indeg = new Int32Array(n + 1);
for (const frag of fragments) {
for (let i = 0; i + 1 < frag.length; i++) {
const a = frag[i], b = frag[i + 1];
if (!after[a].has(b)) {
after[a].add(b);
indeg[b]++;
}
}
}
let ready = [];
for (let label = 1; label <= n; label++) if (indeg[label] === 0) ready.push(label);
let placed = 0;
while (ready.length > 0) {
if (ready.length > 1) return false;
const label = ready.pop();
if (label !== order[placed]) return false;
placed++;
for (const nxt of after[label]) {
if (--indeg[nxt] === 0) ready.push(nxt);
}
}
return placed === n;
}A shortcut without building the graph
There is a neat equivalent test. A topological order is the only one exactly when every pair of neighbours in it is joined by an edge. If some neighbouring pair x, y had no edge, you could swap them and still satisfy every constraint. So: first confirm that every fragment agrees with the proposed order (positions increase along each fragment). Then collect the neighbouring pairs from all fragments and check that each neighbouring pair of the order is among them.
def is_only_order_pairs(order, fragments):
pos = {label: i for i, label in enumerate(order)}
linked = set()
for frag in fragments:
for a, b in zip(frag, frag[1:]):
if pos[a] > pos[b]: # the order breaks this fragment
return False
linked.add((a, b))
return all((order[i], order[i + 1]) in linked for i in range(len(order) - 1))Skip the validity check and this shortcut gives wrong answers. With the order [1,2,3] and fragments [1,2], [2,3], [3,1], every neighbouring pair is present, yet the fragments form a cycle and no order fits at all. The position test catches the 3 before 1 fragment and returns false.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Every permutation | O(n! × (n + L)) | O(n) |
| Kahn's algorithm with a single-label frontier | O(n + L) | O(n + L) |
| Validity check plus neighbouring pairs | O(n + L) | O(n + L) |
Edge cases
- A label that appears in no fragment: with n of 2 or more it has in-degree zero alongside another label at some point, so the answer is false.
- n = 1: one arrangement, so true, whether or not a fragment mentions the label.
- Fragments of length one: they add no edges, only the information that the label exists.
- The same pair in several fragments: store it once, or count and decrement it consistently.
- Fragments that contradict each other (a cycle): Kahn stops early and the count check returns false.
- A fragment that contradicts the proposed order: the forced label does not match, so false.
Common mistakes
- Adding edges between every pair inside a fragment instead of neighbours only. It is still correct but turns O(L) into O(L²) per fragment.
- Checking the frontier size only at the start, not at every step.
- Producing a topological order and comparing it with the proposed one, which says nothing about whether another order exists.
- Forgetting the final count check, which misses cycles.
- Using the neighbouring-pair shortcut without first checking that every fragment agrees with the order.
Follow-up questions
- Count how many valid orders exist. That is much harder in general. For small n, a dynamic program over subsets of placed labels counts them.
- Return a second valid order when the answer is false. At the first step with two ready labels, pick the one the proposed order did not, then finish with ordinary Kahn's algorithm.
- Labels are strings, not 1 to n. Use maps instead of arrays and collect the label set from the order.
- Fragments arrive one by one. After each new fragment, the shortcut lets you track which neighbouring pairs of the order are covered and how many are still missing.
How to explain it out loud
Fictional example
- Candidate
- Each fragment gives me edges between neighbours. Any valid arrangement is a topological order of that graph.
- Candidate
- In Kahn's algorithm, the ready set is everything that could go next. If it ever has two labels, I could pick either, so the order isn't unique.
- Interviewer
- What if a label never shows up in a fragment?
- Candidate
- It starts with in-degree zero, next to whatever else is ready, so I'd see two ready labels and return false, unless n is one.
- Candidate
- I also compare each forced label with the proposed order and check that all n came out, which catches cycles. Linear in n plus the fragment lengths.
Related problems
Parallel Courses uses the same in-degree counting but lets many labels share a level, counting levels instead of forbidding them. Redundant Connection II asks a different structural question about a directed graph: which edge stops it being a rooted tree. For a graph walk that copies rather than orders nodes, see Clone Graph.
Practicing it with Natively
The insight to rehearse is the sentence about Kahn having a choice. While you work through problems on a Mac or Windows PC, Natively can read the fragments from a screenshot, suggest the single-label frontier check and the missing-label edge case, and keep a transcript of your explanation so you can hear whether the uniqueness argument came out clearly. The AI interview assistant page explains the practice setup.
Questions people ask
How do you solve Sequence Reconstruction?
Add an edge between neighbouring labels in each fragment, then run Kahn's algorithm. If two labels are ever ready at once, or the forced label differs from the proposed order, or fewer than n labels come out, return false.
When is a topological order unique?
Exactly when every pair of neighbours in the order is joined by an edge. If some neighbouring pair is not, the two can be swapped and the order still satisfies every constraint.
What is the time complexity of Sequence Reconstruction?
O(n + L) time and space, where n is the number of labels and L is the total length of all fragments.
What if a label appears in no fragment?
Then it can be placed anywhere, so the order is not unique whenever there are two or more labels. Kahn's algorithm sees two ready labels and returns false.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
