Count minimum cost in graph
Last updated: December 17, 2025
Quick Overview
Given a weighted, directed graph represented by an adjacency list, write a function to calculate the minimum cost to traverse from a specified source node to a target node. The function should return the minimum cost as an integer, or -1 if there is no valid path. You may assume that the graph does not contain negative weight cycles.
9
12
3,873 solved
Given a weighted, directed graph represented by an adjacency list, write a function to calculate the minimum cost to traverse from a specified source node to a target node. The function should return the minimum cost as an integer, or -1 if there is no valid path. You may assume that the graph does not contain negative weight cycles.
This coding problem is frequently asked during Take-home Project at LinkedIn. The interviewer is testing your ability to translate a problem into clean, working code while discussing time and space complexity. LinkedIn expects candidates to write production-quality code, not just solve the puzzle.
What the Interviewer Expects
- Quickly identify the optimal approach and its theoretical basis
- Handle complex algorithm design with multiple interacting components
- Write concise, elegant code under time pressure
- Prove correctness of your approach and discuss alternative solutions
- Optimize beyond the obvious: discuss constant factor improvements
- Address follow-up variations and explain how the solution generalizes
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Can you solve this in a single pass?
- How would your solution change if the input was sorted?
- Can you solve this iteratively instead of recursively (or vice versa)?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Problem Analysis
This problem can be effectively solved using Dijkstra's algorithm, which is optimal for finding the shortest path in a weighted graph with non-negative weights. The algorithm employs a priority queue ...
Approach
-
Graph Representation: First, represent the graph as an adjacency list. Each node will map to a list of tuples, where each tuple contains a neighboring node and the cost to reach it.
-
**Init...