A* Search Algorithm: Pathfinding for Interviews
A* is the gold standard for pathfinding in interviews. It combines Dijkstra's optimality with heuristic-guided search to find shortest paths faster.
How A* Works
A* maintains two values for each node:
g(n): Actual cost from start to nh(n): Estimated cost from n to goal (heuristic)f(n) = g(n) + h(n): Total estimated cost
A* always expands the node with the lowest f(n).
Implementation
import heapq
def a_star(graph, start, goal, heuristic):
open_set = [(heuristic(start, goal), 0, start)]
came_from = {}
g_score = {start: 0}
while open_set:
f, g, current = heapq.heappop(open_set)
if current == goal:
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.append(start)
return path[::-1]
for neighbor, cost in graph[current]:
tentative_g = g_score[current] + cost
if neighbor not in g_score or tentative_g < g_score[neighbor]:
came_from[neighbor] = current
g_score[neighbor] = tentative_g
f_score = tentative_g + heuristic(neighbor, goal)
heapq.heappush(open_set, (f_score, tentative_g, neighbor))
return None # No path found
Heuristic Design
The heuristic is critical. It must be:
- Admissible: Never overestimates the true cost (guarantees optimality)
- Consistent: h(n) ≤ cost(n, n') + h(n') for all neighbors n' (guarantees efficiency)
Common Heuristics for Grids
Manhattan Distance (4-directional movement):
def manhattan(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
Euclidean Distance (any direction):
def euclidean(a, b):
return math.sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)
Chebyshev Distance (8-directional movement):
def chebyshev(a, b):
return max(abs(a[0] - b[0]), abs(a[1] - b[1]))
A* vs Dijkstra
Dijkstra is A with h(n) = 0. A with an admissible heuristic:
- Explores fewer nodes
- Finds the optimal path
- Still O(E log V) worst case, but typically much faster in practice
A* vs BFS
BFS is A with uniform edge costs and h(n) = 0. Use A when:
- Edge costs vary
- You have a good heuristic
Bidirectional A*
Search from both start and goal, meeting in the middle:
def bidirectional_a_star(graph, start, goal, heuristic):
# Two priority queues, two g_scores, two came_from maps
# Expand from both sides alternately
# Check if current node is in other side's closed set
# Implementation follows similar pattern to unidirectional
pass
Interview Tips
- Implement Dijkstra first. A* is a natural extension. Show you understand both.
- Discuss admissibility. Explain why your heuristic never overestimates.
- Edge cases: No path exists, start equals goal, negative edges (A* doesn't handle these).
- Common follow-ups: "What if we need the k shortest paths?" (Yen's algorithm), "How to handle dynamic obstacles?" (D* Lite).
Time Complexity
Worst case: O(E log V) with a binary heap
Best case: O(E) with a perfect heuristic
Space: O(V)
Master the most common coding interview patterns to ace your technical rounds.
For technical interview preparation, our system design guide is essential reading.
Don't neglect behavioral preparation — see our behavioral interview guide.
Your resume is the first impression — get it right with our resume guide.
{
"@context": "https://schema.org",
"@type": "BlogPosting",
"headline": "A* Search Algorithm: Pathfinding for Interviews",
"description": "A is the gold standard for pathfinding in interviews. It combines Dijkstra's optimality with heuristic-guided search to find shortest paths faster.",
"datePublished": "2026-03-21",
"author": {
"@type": "Organization",
"name": "CodeSwiftr Team"
},
"url": "https://codeswiftr.com/blog/a-star-search-pathfinding"
}
Related Reading
- AI Interview Practice Tools Comparison
- Amazon Leadership Principles Interview Guide
- Airbnb Engineering Deep Dive
- API Design Interview Guide
- Bit Manipulation Interview Guide
Elevate your prep with AI. Practice your technical interviews with CodeSwiftr and get real-time feedback on your delivery, STAR method compliance, and technical depth.
Explore Related Topics
- Bloom Filters & Probabilistic Data Structures for Interviews
- Network Flow Algorithms: Max Flow to Bipartite Matching
- Skip Lists: Concurrent Data Structures for Interviews
Related Guides
- System Design Interview Guide
- Amazon Leadership Principles Interview Questions
- Behavioral Interview Star Method
Ready to practice? Start your free mock interview on CodeSwiftr.
{
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": [
{
"@type": "Question",
"name": "What is the A* algorithm and when should you use it instead of Dijkstra's?",
"acceptedAnswer": {
"@type": "Answer",
"text": "A is an informed graph search algorithm that finds the shortest path from a start node to a goal node. It combines Dijkstra's cost-so-far (g(n)) with a heuristic estimate of remaining cost (h(n)) to prioritize exploration toward the goal. f(n) = g(n) + h(n) — A expands the node with the lowest f(n). Use A instead of Dijkstra's when you have domain knowledge that provides an admissible heuristic (one that never overestimates the remaining cost). For grid pathfinding, Manhattan distance (|dx| + |dy|) is the classic heuristic. When the heuristic is zero everywhere, A degrades to Dijkstra's. A* is significantly faster than Dijkstra's in practice for pathfinding problems because it avoids exploring nodes in the wrong direction. Time complexity is O(b^d) where b is branching factor and d is depth, but a good heuristic dramatically reduces the explored space."
}
},
{
"@type": "Question",
"name": "What makes a heuristic admissible for the A* algorithm?",
"acceptedAnswer": {
"@type": "Answer",
"text": "An admissible heuristic never overestimates the true cost to reach the goal — it is always optimistic. If h(n) is admissible, A* is guaranteed to find the optimal (shortest) path. For grid movement: Manhattan distance is admissible when movement is restricted to 4 directions (no diagonals), because you must traverse at least |dx| + |dy| steps. Euclidean distance is admissible for any movement because the straight-line distance is always the minimum possible. Chebyshev distance is admissible for 8-directional grid movement. An inadmissible heuristic can find paths faster but may miss the optimal solution. A consistent (monotone) heuristic additionally satisfies the triangle inequality — h(n) <= cost(n, neighbor) + h(neighbor) — which guarantees that once a node is expanded, the optimal path to it has been found, eliminating the need to re-expand nodes."
}
},
{
"@type": "Question",
"name": "In what interview contexts does A* search appear?",
"acceptedAnswer": {
"@type": "Answer",
"text": "A appears in interviews in several forms: explicit pathfinding questions (find the shortest path in a weighted grid with obstacles), implicit graph problems where BFS is insufficient because edges have different weights (weighted puzzle problems), game development system design questions (how would you implement NPC pathfinding?), and robotics or autonomous systems questions. For unweighted grids, BFS is simpler and sufficient — don't reach for A when BFS works. A is specifically valuable when: the graph is weighted, the goal is a specific target node (not all-nodes reachability), and you have a meaningful heuristic. In interviews, demonstrating you know when NOT to use A (e.g., unweighted BFS problems) shows stronger algorithmic judgment than always reaching for the fanciest algorithm."
}
},
{
"@type": "Question",
"name": "How does A* relate to other graph search algorithms like BFS, DFS, and Dijkstra's?",
"acceptedAnswer": {
"@type": "Answer",
"text": "The graph search family: DFS explores as deep as possible along each branch before backtracking — low memory (O(depth)) but doesn't find shortest paths and can get stuck in infinite loops on graphs with cycles. BFS explores all nodes at distance k before distance k+1 — finds shortest path in unweighted graphs, O(V+E) time and O(V) space. Dijkstra's finds shortest paths in weighted graphs with non-negative edges — uses a min-heap priority queue ordered by cost-so-far, O((V+E) log V) time. A is Dijkstra's with a heuristic to guide exploration toward the goal — same correctness guarantees with better practical performance when a good heuristic exists. Bidirectional A searches from both start and goal simultaneously, meeting in the middle — useful for very long paths where one-directional search explores too much space."
}
}
]
}