Skip to contentKEEP THE CRAFTTHE SANCTUARY

Search

Choose a search policy from the shape of the space: unsorted items, a monotone boundary, or reachable graph states. State the goal, frontier, duplicate key and optimality premise before picking a data structure.

1 practice exercise1 interview problem

Recognize it when The answer is one candidate among explicit values or states generated by transitions.

Checking your account…

Search Code Labs

Define the Search Space

Search operates over explicit items, numeric candidates, or implicit states connected by transitions. Define what one state means and which states are legal before choosing an algorithm.

Choose a Frontier Policy

A FIFO queue explores by hop distance for unit-cost edges, a stack by branch depth, and a priority queue by current best tentative cost under the chosen weighted-path algorithm. The data structure is the search policy, not an implementation detail.

Trace a Search Frontier

Reference
from collections import deque

def queue_frontier_trace(adjacency,start):
    if start==-1:return []
    queue=deque([start]); seen={start}; trace=[]
    while queue:
        trace.append(list(queue)); node=queue.popleft()
        for neighbor in adjacency[node]:
            if neighbor not in seen: seen.add(neighbor); queue.append(neighbor)
    return trace
Practice

Implement queue_frontier_trace(adjacency,start). Return queue contents before each BFS removal. Use adjacency lists whose neighbor indices are valid vertices; start must be a valid vertex index or the explicit -1 no-source sentinel.

Public tests

  • Expose frontier policy

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace a Search Frontier

from collections import deque

def queue_frontier_trace(adjacency,start):
    if start==-1:return []
    queue=deque([start]); seen={start}; trace=[]
    while queue:
        trace.append(list(queue)); node=queue.popleft()
        for neighbor in adjacency[node]:
            if neighbor not in seen: seen.add(neighbor); queue.append(neighbor)
    return trace

Read the Queue Before Each Expansion

The queue-trace Lab illustrates one policy in the search family. Predict the frontier for this three-node graph; the edge from 2 to 1 must not duplicate pending work.

Step Executed statement State Why
Start queue=deque([start]); seen={start}; trace=[] queue=[0], seen={0} The source is discovered exactly once.
Expand 0 trace.append(list(queue)); node=queue.popleft(); seen.add(neighbor); queue.append(neighbor) trace=[[0]], then queue=[2, 1] Neighbor order controls ties within the same edge distance.
Expand 2 node=queue.popleft(); if neighbor not in seen queue=[1], seen={0, 1, 2} Its neighbor 1 is already discovered, so it is not enqueued again.
Finish return trace [[0], [2, 1], [1]] Each row shows pending work before removal, not the completed path.
Print Output
print(queue_frontier_trace([[2, 1], [], [1]], 0)) [[0], [2, 1], [1]]

This trace is a policy demonstration, not a proof that BFS solves every search task. Explain which order property the actual question needs, then select the least complex algorithm that supplies it.

Recognize Goal and Repeated State

Test the goal at a consistent point and record visited state before adding duplicates to the frontier. The visited key must include every dimension that changes future behavior.

Find a Reachable Goal

Reference
from collections import deque

def reachable_goal(adjacency,start,goals):
    if start==-1:return -1
    queue=deque([start]); seen={start}
    while queue:
        node=queue.popleft()
        if node in goals:return node
        for neighbor in adjacency[node]:
            if neighbor not in seen:seen.add(neighbor);queue.append(neighbor)
    return -1
Practice

Implement reachable_goal(adjacency,start,goals). Return the first goal found by BFS or -1. Use adjacency lists whose neighbor indices are valid vertices; start must be a valid vertex index or the explicit -1 no-source sentinel.

Public tests

  • Stop when the goal contract is met

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Find a Reachable Goal

from collections import deque

def reachable_goal(adjacency,start,goals):
    if start==-1:return -1
    queue=deque([start]); seen={start}
    while queue:
        node=queue.popleft()
        if node in goals:return node
        for neighbor in adjacency[node]:
            if neighbor not in seen:seen.add(neighbor);queue.append(neighbor)
    return -1

Use linear search for unsorted finite items, binary search for monotone ordered spaces, and graph search for generated transitions with possible branching. Complexity follows inspected states plus generated edges.

Explain It in an Interview

Say: “A state is…, neighbors are…, and this frontier policy guarantees… . I stop under this goal predicate and deduplicate with this key.” Then state completeness, optimality assumptions, and worst-case frontier space.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Linear lookupO(n)O(n)No ordering premise.
Monotone boundary lookupO(log n)O(log n)Constant-cost predicate and random access.
BFS/DFS graph traversalO(V + E)O(V + E)Adjacency lists and visited bookkeeping; trace snapshots add copying.

Space

O(1) for a scan or iterative bisection; O(V) frontier/visited storage for a graph.

Assumptions

  • The frontier-trace Lab copies each queue, so its total output size can be quadratic in V.
  • A weighted path may require Dijkstra or Bellman-Ford rather than this BFS drill.

Invariants Worth Saying Aloud

  1. The frontier contains discovered work still eligible for expansion.
  2. A rejected or deduplicated state must have no unexplored role relevant to the answer.

When To Use Or Avoid Search

Use It When

  • Use a scan for one unsorted lookup, bisection for a proved monotone space, and graph traversal for generated neighbors.
  • Use a visited key that captures every state dimension affecting future moves.

Choose Another Tool When

  • Do not assume a queue finds the cheapest weighted path; FIFO orders edge count only.
  • Do not sort away original positions when the requested answer is an original index.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Losing original positions by sorting first

Sorting [7,2,9] moves 7 from index 0 to index 1. A sorted position does not answer an original-index question.

Prevent it: Preserve the original sequence or carry original indexes.

Avoid

answer = sorted(values).index(target)

Use instead

answer = values.index(target)

Forgetting a state dimension in the visited key

Two positions at the same cell but with different remaining keys have different possible futures. A cell-only key merges them.

Prevent it: Include the relevant inventory or other state dimension in the key.

Avoid

seen.add(cell)

Use instead

seen.add((cell, keys))

Using a stack when nearest-in-edges is required

With nearer goal (1,1) before farther goal (2,2), popping the tail chooses distance 2 first. This violates nearest-in-edge-distance ordering.

Prevent it: Use popleft for FIFO exploration and preserve the declared neighbor order.

Avoid

node = frontier.pop()

Use instead

node = frontier.popleft()

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.