Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The A* Search proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Order a single-goal frontier by known cost g plus a justified lower bound h. Keep g separate from priority, reopen improved states when needed, and tie the Manhattan heuristic to orthogonal unit moves.
1 practice exercise1 interview problem
Recognize it when One start-to-goal route has a useful lower-bound estimate.
Checking your account…
A* orders frontier states by f = g + h: exact cost g from the start plus estimated remaining cost h to the goal. The heuristic changes exploration order, not the path-cost definition.
An admissible heuristic never overestimates the true remaining cost. A consistent heuristic additionally obeys a triangle-like inequality, making finalized-state handling simpler.
def priority_trace(costs,heuristics):
return [[node,costs[node],heuristics[node],costs[node]+heuristics[node]] for node in sorted(costs,key=lambda node:(costs[node]+heuristics[node],node))]Implement priority_trace(costs,heuristics). Return [node,g,h,f] sorted by f then node for matching dictionaries.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def priority_trace(costs,heuristics):
return [[node,costs[node],heuristics[node],costs[node]+heuristics[node]] for node in sorted(costs,key=lambda node:(costs[node]+heuristics[node],node))]Store best known g separately from heap priorities. If a cheaper path reaches a state, update it and push a new entry; skip stale entries whose g no longer matches.
import heapq
def grid_a_star(grid,start,goal):
rows,cols=len(grid),len(grid[0]);cost={tuple(start):0};heap=[(abs(start[0]-goal[0])+abs(start[1]-goal[1]),0,tuple(start))]
while heap:
_,current,node=heapq.heappop(heap)
if current!=cost[node]:continue
if node==tuple(goal):return current
for dr,dc in ((1,0),(-1,0),(0,1),(0,-1)):
neighbor=(node[0]+dr,node[1]+dc)
if 0<=neighbor[0]<rows and 0<=neighbor[1]<cols and grid[neighbor[0]][neighbor[1]]==0:
candidate=current+1
if candidate<cost.get(neighbor,float("inf")):
cost[neighbor]=candidate;heuristic=abs(neighbor[0]-goal[0])+abs(neighbor[1]-goal[1]);heapq.heappush(heap,(candidate+heuristic,candidate,neighbor))
return -1Implement grid_a_star(grid,start,goal). Zero cells are open, one cells blocked; return shortest orthogonal step count or -1 using Manhattan heuristic. grid is a nonempty rectangular grid; start and goal are in-bounds open cells.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
import heapq
def grid_a_star(grid,start,goal):
rows,cols=len(grid),len(grid[0]);cost={tuple(start):0};heap=[(abs(start[0]-goal[0])+abs(start[1]-goal[1]),0,tuple(start))]
while heap:
_,current,node=heapq.heappop(heap)
if current!=cost[node]:continue
if node==tuple(goal):return current
for dr,dc in ((1,0),(-1,0),(0,1),(0,-1)):
neighbor=(node[0]+dr,node[1]+dc)
if 0<=neighbor[0]<rows and 0<=neighbor[1]<cols and grid[neighbor[0]][neighbor[1]]==0:
candidate=current+1
if candidate<cost.get(neighbor,float("inf")):
cost[neighbor]=candidate;heuristic=abs(neighbor[0]-goal[0])+abs(neighbor[1]-goal[1]);heapq.heappush(heap,(candidate+heuristic,candidate,neighbor))
return -1Run the existing grid Lab with a vertical wall. Trace the forced route down, across and back up. Distinguish the cost table from the heap’s heuristic priority at every point.
| Step | Executed statement | State | Why |
|---|---|---|---|
| Initial priority | heap=[(abs(start[0]-goal[0])+abs(start[1]-goal[1]),0,tuple(start))] |
start=(0,0), g=0,h=2,f=2 |
The apparent two-step route is blocked, but 2 remains a lower bound. |
| Pop source | _,current,node=heapq.heappop(heap) |
current=0, node=(0,0) |
The popped tuple supplies the current real path cost before neighbor candidates are computed. |
| First detour | candidate=current+1;cost[neighbor]=candidate;heuristic=abs(neighbor[0]-goal[0])+abs(neighbor[1]-goal[1]);heapq.heappush(heap,(candidate+heuristic,candidate,neighbor)) |
after start expansion: (1,0) has g=1,h=3,f=4 |
A necessary move away from the goal increases h; optimal search must still allow it. |
| Around the wall | _,current,node=heapq.heappop(heap);candidate=current+1;cost[neighbor]=candidate;heuristic=abs(neighbor[0]-goal[0])+abs(neighbor[1]-goal[1]);heapq.heappush(heap,(candidate+heuristic,candidate,neighbor)) |
after successive expansions: (2,0),(2,1),(2,2) have g=2,3,4 |
Open-cell checks reject both central wall cells. |
| Reach goal | _,current,node=heapq.heappop(heap);return current |
goal=(0,2), current=6 |
The returned value is the real six-step route, not the initial heuristic 2. The return executes in the actual node==goal branch. |
| Output | |
|---|---|
print(grid_a_star([[0, 1, 0], [0, 1, 0], [0, 0, 0]], [0, 0], [0, 2])) |
6 |
The priority-only Lab isolates g+h ordering; it does not establish heuristic admissibility. Prove the estimate under the actual moves and weights before treating a smaller f as safe guidance.
Choose A* when a meaningful admissible heuristic guides a single-pair search. Choose Dijkstra when no useful heuristic exists or distances to many targets are needed. With h = 0, A* is Dijkstra.
Say: “g is known cost, h is a lower bound on remaining cost, so f prioritizes promising states without excluding an optimal path.” State admissibility or consistency, stale entries, unreachable output, and heuristic cost.
Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The A* Search proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| A* on this unit grid with Manhattan | O(RC log(RC)) | O(RC log(RC)) | Manhattan is consistent and the grid has O(RC) edges; a different heuristic/model needs its own bound. |
| Priority-only dictionary Lab | O(k log(k+1)) | O(k log(k+1)) | k matching cost/heuristic keys with bounded comparison and ordinary dictionary lookup; output sorts by g+h then node. This does not certify a heuristic. |
O(RC) costs and frontier for this fixed-degree consistent grid. The priority-only Lab uses O(k) sorted-key and output storage.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
Manhattan 2 ignores a wall forcing a four-step detour. It is a lower bound, not a completed path.
Prevent it: Return g at a current goal pop, not h at the start.
answer = heuristicanswer = goal_costWhere you will hit this: Navigate a Grid with A*(opens in a new tab)
Greedy best-first picks a nearly-goal state with g=9,h=1 over a cheaper promising state with g=2,h=3.
Prevent it: Use f=g+h when claiming A* path optimality.
picked = min(states, key=lambda row: row[2])picked = min(states, key=lambda row: row[1] + row[2])Where you will hit this: Navigate a Grid with A*(opens in a new tab)
A diagonal unit move from (0,0) to (1,1) costs 1, while Manhattan is 2 and overestimates.
Prevent it: For eight-direction unit moves use a suitable Chebyshev lower bound instead.
h = abs(dx) + abs(dy)h = max(abs(dx), abs(dy))Where you will hit this: Lowest Common Ancestor in a BST(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27