Skip to main content

Reconstruct Itinerary

Given tickets array where each [from, to] is a flight Start from "JFK" and return itinerary in lexical order Example: [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] => ["JFK","MUC","LHR","SFO","SJC"]

Reconstruct Itinerary rewards structured search and good pruning more than raw cleverness. It's a hard one for a reason: it stresses structured exploration when the rules pile up. The gotcha is duplicates and dead ends—good pruning and ordering rules make this manageable.

Examples

You write

find_itinerary(tickets: List[List[str]])

  1. Example 1

    Input
    tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
    returns
    ["JFK","MUC","LHR","SFO","SJC"]
  2. Example 2

    Input
    tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
    returns
    ["JFK","ATL","JFK","SFO","ATL","SFO"]

The pattern behind it

Backtracking

I reach for it when

  • The question asks for all combinations, permutations or placements.
  • You make a choice, explore it, and may need to take it back.

Say this before you type. Say the choice, the stopping rule, and the earliest moment you can prune.

All 15 Backtracking problems

BFS & DFS

I reach for it when

  • You walk a grid, a graph or a tree and visit each cell once.
  • The word shortest appears and every step costs the same.

Say this before you type. Say why breadth or depth fits, and exactly when a cell counts as visited.

All 52 BFS & DFS problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Reconstruct Flight Itineraryhard