Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Start free
SQL Shortest Paths from Node 1
00:00
5 left

SQL Shortest Paths from Node 1

HardSQL · PostgreSQL

Problem

How would you solve a graph-focused data structure and algorithm problem end to end, including edge cases and complexity?

For this SQL exercise, treat the data as a directed graph and start traversal at node 1. Return the shortest reachable path to every node, while safely handling cycles and nodes that cannot be reached.

Output

  1. One row per node, including the start node and unreachable nodes.
  2. Columns: node_id, node_name, shortest_hops, and path.
  3. Use NULL for unreachable nodes and order by node_id ascending.

Output details

  • Represent path as an integer array listing node IDs from 1 through the destination, using [1] for the start node.
  • For equal-length paths, select the lexicographically smallest path.
  • Preserve NULL in node_name when a node has no name.

Schema

graph_nodes
ColumnTypeDescription
node_idPKINTUnique graph node identifier
node_nameVARCHAR(100)Display name for the node
graph_edges
ColumnTypeDescription
edge_idPKINTUnique directed edge identifier
from_node_idINTSource node of the directed edge
to_node_idINTDestination node of the directed edge
Tablesgraph_nodesgraph_edges
Interviewer

Whenever you're ready, walk me through your approach or go straight to the code. The requirements and the two tables are in the Question tab.

Sign up free to run or submit. Log in
CodePostgreSQL
Sign up free to run your code. Your draft is saved.Run with a free accountLog inLn 1
Run your query to see results here.