Data Structures & Algorithms

Leetcode 787 Cheapest Flights Within K Stops Java Solution

// SOLVING THIS WITH AN AI ASSISTANT (2026)

If you are working through this problem with an AI coding assistant — Claude, ChatGPT, Cursor chat, Gemini, GitHub Copilot, Aider, or any agent — the goal isn’t to ask for the answer. It is to use the tool to understand the pattern. The prompt sequence I’d run:

  1. Spec it back to me first. “In your own words, what is this problem actually testing? What’s the smallest example that fails the naive approach?”
  2. Brute-force first, optimize after. “Write the simplest correct solution, even if it’s O(n²). Don’t optimize. Just make it correct, with comments explaining each step.”
  3. Ask for the upgrade. “Now show me the optimal solution. What insight makes it possible? What pattern is this an instance of?”
  4. Stress-test it. “Generate 10 edge cases — empty input, single element, duplicates, max size, sorted, reverse-sorted. Run my solution against each.”

The pattern matters more than the answer. If the agent just hands you optimized code, you’ve trained yourself to lose interviews.

There are n cities connected by m flights. Each flight starts from city u and arrives at v with a price w.

Now given all the cities and flights, together with starting city src and the destination dst, your task is to find the cheapest price from src to dst with up to k stops. If there is no such route, output -1.

Example 1:
Input: 
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
Output: 200
Explanation: 
The graph looks like this:
Weighted Directed Graph
The cheapest price from city 0 to city 2 with at most 1 stop costs 200, as marked red in the picture.

Solution:



class Solution {
    public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
        if(flights.length==0) return -1;
        
        HashMap<Integer, List<int []>> graph = new HashMap<>();
        
        for(int[] flight: flights){
            
            if(!graph.containsKey(flight[0])){
                graph.put(flight[0], new ArrayList<int[]>());
            }
            
            graph.get(flight[0]).add(new int[]{flight[1], flight[2]});
        }
        
        
        PriorityQueue<Node> q = new PriorityQueue<Node>((a,b) -> (a.cost - b.cost));
        
        q.add(new Node(src, 0, -1));
        
        while(!q.isEmpty()){
            
            Node curr = q.poll();
            
            if(curr.city == dst){
                return curr.cost;
            }
            
            if(curr.stop<K){
                List<int []> nexts = graph.getOrDefault(curr.city, new ArrayList<int[]>());
                
                for(int[] next: nexts){
                    q.add(new Node(next[0], curr.cost+next[1], curr.stop+1));
                }
            }
        }     
        return -1;
    }
}
class Node {
    int city;
    int cost;
    int stop;   
    public Node(int city, int cost, int stop){
        this.city = city;
        this.cost = cost;
        this.stop = stop;
    }
}

Here is the video explanation:




For the AI-native engineering side of HackerHeap — building MCP servers, comparing agents (Claude Code, Cursor, Windsurf, Codex, Gemini, Copilot), and weekly working code — see the Friday Build newsletter and the MCP archive.

rajendra

Recent Posts

HackerHeap is back: building with AI agents in 2026

HackerHeap is back: a multi-platform resource for working developers building with AI coding agents. We…

1 week ago

LeetCode Maximum Erasure Value

// SOLVING THIS WITH AN AI ASSISTANT (2026)If you are working through this problem with…

4 years ago

Largest Unique Number Java Solution

// BUILDING THIS WITH AN AI AGENT (2026)Whether you are using Claude Code, Cursor, Windsurf,…

5 years ago

Jump Search Algorithm In Java

// SOLVING THIS WITH AN AI ASSISTANT (2026)If you are working through this problem with…

6 years ago

Knuth Morris Pratt Pattern Search Algorithm

// SOLVING THIS WITH AN AI ASSISTANT (2026)If you are working through this problem with…

6 years ago

Binary Search Algorithm In Java

// SOLVING THIS WITH AN AI ASSISTANT (2026)If you are working through this problem with…

6 years ago

This website uses cookies.