Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #444: Sequence Reconstruction

In this guide, we solve Leetcode #444 Sequence Reconstruction in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given an integer array nums of length n where nums is a permutation of the integers in the range [1, n]. You are also given a 2D integer array sequences where sequences[i] is a subsequence of nums.

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: Graph, Topological Sort, Array

Intuition

The data forms a graph, so we should explore nodes and edges systematically.

A traversal ensures we visit each node once while maintaining the needed state.

Approach

Build an adjacency list and traverse with BFS or DFS.

Aggregate results as you visit nodes.

Steps:

  • Build the graph.
  • Traverse with BFS/DFS.
  • Accumulate the required output.

Example

Input: nums = [1,2,3], sequences = [[1,2],[1,3]] Output: false Explanation: There are two possible supersequences: [1,2,3] and [1,3,2]. The sequence [1,2] is a subsequence of both: [1,2,3] and [1,3,2]. The sequence [1,3] is a subsequence of both: [1,2,3] and [1,3,2]. Since nums is not the only shortest supersequence, we return false.

Python Solution

class Solution: def sequenceReconstruction( self, nums: List[int], sequences: List[List[int]] ) -> bool: n = len(nums) g = [[] for _ in range(n)] indeg = [0] * n for seq in sequences: for a, b in pairwise(seq): a, b = a - 1, b - 1 g[a].append(b) indeg[b] += 1 q = deque(i for i, x in enumerate(indeg) if x == 0) while len(q) == 1: i = q.popleft() for j in g[i]: indeg[j] -= 1 if indeg[j] == 0: q.append(j) return len(q) == 0

Complexity

The time complexity is O(n+m)O(n + m)O(n+m), and the space complexity is O(n+m)O(n + m)O(n+m). The space complexity is O(n+m)O(n + m)O(n+m).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy