Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Shortest distance between two cells in a matrix or grid
Next article icon

Maximum cost path from source node to destination node via at most K intermediate nodes

Last Updated : 21 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a directed weighted graph consisting of N vertices and an array Edges[][], with each row representing two vertices connected by an edge and the weight of that edge, the task is to find the path with the maximum sum of weights from a given source vertex src to a given destination vertex dst, made up of at most K intermediate vertices. If no such path exists, then print -1.

Examples:

Input: N = 3, Edges[][] = {{0, 1, 100}, {1, 2, 100}, {0, 2, 500}}, src = 0, dst = 2, K = 0
Output: 500
Explanation:
 


Path 0 → 2: The path with maximum weight and at most 0 intermediate nodes is of weight 500.

 

Approach: The given problem can be solved by using BFS(Breadth-First Search) Traversal. Follow the steps below to solve the problem:

  • Initialize the variable, say ans, to store the maximum distance between the source and the destination node having at most K intermediates nodes.
  • Initialize an adjacency list of the graph using the edges.
  • Initialize an empty queue and push the source vertex into it. Initialize a variable, say lvl, to store the number of nodes present in between src and dst.
  • While the queue is not empty and lvl is less than K + 2 perform the following steps:
    • Store the size of the queue in a variable, say S.
    • Iterate over the range [1, S] and perform the following steps:
      • Pop the front element of the queue and store it in a variable, say T.
      • If T is the dst vertex, then update the value of ans as the maximum of ans and the current distance T.second.
      • Traverse through all the neighbors of the current popped node and check if the distance of its neighbor is greater than the current distance or not. If found to be true, then push it in the queue and update its distance.
    • Increase the value of lvl by 1.
  • After completing the above steps, print the value of ans as the resultant maximum distance.

Below is the implementation of the above approach:

C++
// C++ program for the above approach  #include <bits/stdc++.h> using namespace std;  // Function to find the longest distance // from source to destination with at // most K intermediate nodes int findShortestPath(     int n, vector<vector<int> >& edges,     int src, int dst, int K) {     // Initialize the adjacency list     vector<vector<pair<int, int> > > adjlist(         n, vector<pair<int, int> >());      // Initialize a queue to perform BFS     queue<pair<int, int> > q;      unordered_map<int, int> mp;      // Store the maximum distance of     // every node from source vertex     int ans = INT_MIN;      // Initialize adjacency list     for (int i = 0; i < edges.size(); i++) {          auto edge = edges[i];          adjlist[edge[0]].push_back(             make_pair(edge[1], edge[2]));     }      // Push the first element into queue     q.push({ src, 0 });      int level = 0;      // Iterate until the queue becomes empty     // and the number of nodes between src     // and dst vertex is at most to K     while (!q.empty() && level < K + 2) {          // Current size of the queue         int sz = q.size();          for (int i = 0; i < sz; i++) {              // Extract the front             // element of the queue             auto pr = q.front();              // Pop the front element             // of the queue             q.pop();              // If the dst vertex is reached             if (pr.first == dst)                 ans = max(ans, pr.second);              // Traverse the adjacent nodes             for (auto pr2 : adjlist[pr.first]) {                  // If the distance is greater                 // than the current distance                 if (mp.find(pr2.first)                         == mp.end()                     || mp[pr2.first]                            < pr.second                                  + pr2.second) {                      // Push it into the queue                     q.push({ pr2.first,                              pr.second                                  + pr2.second });                     mp[pr2.first] = pr.second                                     + pr2.second;                 }             }         }          // Increment the level by 1         level++;     }      // Finally, return the maximum distance     return ans != INT_MIN ? ans : -1; }  // Driver Code int main() {     int n = 3, src = 0, dst = 2, k = 1;     vector<vector<int> > edges         = { { 0, 1, 100 },             { 1, 2, 100 },             { 0, 2, 500 } };      cout << findShortestPath(n, edges,                              src, dst, k);      return 0; } 
Java
import java.util.*;  class Main {      // Function to find the longest distance     // from source to destination with at     // most K intermediate nodes     public static int findShortestPath(int n, int[][] edges,                                        int src, int dst,                                        int K)     {         // Initialize the adjacency list         List<List<int[]> > adjlist = new ArrayList<>();         for (int i = 0; i < n; i++) {             adjlist.add(new ArrayList<int[]>());         }          // Initialize a queue to perform BFS         Queue<int[]> q = new LinkedList<>();          Map<Integer, Integer> mp = new HashMap<>();          // Store the maximum distance of         // every node from source vertex         int ans = Integer.MIN_VALUE;          // Initialize adjacency list         for (int[] edge : edges) {             adjlist.get(edge[0]).add(                 new int[] { edge[1], edge[2] });         }          // Push the first element into queue         q.add(new int[] { src, 0 });          int level = 0;          // Iterate until the queue becomes empty         // and the number of nodes between src         // and dst vertex is at most to K         while (!q.isEmpty() && level < K + 2) {              // Current size of the queue             int sz = q.size();              for (int i = 0; i < sz; i++) {                  // Extract the front                 // element of the queue                 int[] pr = q.poll();                  // If the dst vertex is reached                 if (pr[0] == dst)                     ans = Math.max(ans, pr[1]);                  // Traverse the adjacent nodes                 for (int[] pr2 : adjlist.get(pr[0])) {                      // If the distance is greater                     // than the current distance                     if (!mp.containsKey(pr2[0])                         || mp.get(pr2[0])                                > pr[1] + pr2[1]) {                          // Push it into the queue                         q.add(new int[] { pr2[0],                                           pr[1] + pr2[1] });                         mp.put(pr2[0], pr[1] + pr2[1]);                     }                 }             }              // Increment the level by 1             level++;         }          // Finally, return the maximum distance         return ans != Integer.MIN_VALUE ? ans : -1;     }      // Driver Code     public static void main(String[] args)     {         int n = 3, src = 0, dst = 2, k = 1;         int[][] edges = { { 0, 1, 100 },                           { 1, 2, 100 },                           { 0, 2, 500 } };          System.out.println(             findShortestPath(n, edges, src, dst, k));     } } 
Python
# Python3 program for the above approach from collections import deque  # Function to find the longest distance # from source to destination with at # most K intermediate nodes def findShortestPath(n, edges, src, dst, K):          # Initialize the adjacency list     adjlist = [[] for i in range(n)]          # Initialize a queue to perform BFS     q = deque()      mp = {}      # Store the maximum distance of     # every node from source vertex     ans = -10**9      # Initialize adjacency list     for i in range(len(edges)):         edge = edges[i]         adjlist[edge[0]].append([edge[1],                                   edge[2]])      # Push the first element into queue     q.append([src, 0])      level = 0      # Iterate until the queue becomes empty     # and the number of nodes between src     # and dst vertex is at most to K     while (len(q) > 0 and level < K + 2):          # Current size of the queue         sz = len(q)          for i in range(sz):                          # Extract the front             # element of the queue             pr = q.popleft()                          # Pop the front element             # of the queue             # q.pop()              # If the dst vertex is reached             if (pr[0] == dst):                 ans = max(ans, pr[1])              # Traverse the adjacent nodes             for pr2 in adjlist[pr[0]]:                                  # If the distance is greater                 # than the current distance                 if ((pr2[0] not in mp) or                    mp[pr2[0]] > pr[1] + pr2[1]):                                            # Push it into the queue                     q.append([pr2[0], pr[1] + pr2[1]])                     mp[pr2[0]] = pr[1] + pr2[1]          # Increment the level by 1         level += 1      # Finally, return the maximum distance     return ans if ans != -10**9 else -1  # Driver Code if __name__ == '__main__':          n, src, dst, k = 3, 0, 2, 1      edges= [ [ 0, 1, 100 ],              [ 1, 2, 100 ],              [ 0, 2, 500 ] ]      print(findShortestPath(n, edges,src, dst, k))  # This code is contributed by mohit kumar 29 
C#
// C# program for the above approach  using System; using System.Collections.Generic;  class GFG {     // Function to find the longest distance     // from source to destination with at     // most K intermediate nodes     static int FindShortestPath(int n, int[][] edges, int src, int dst, int K)     {         // Initialize the adjacency list         List<int[]>[] adjlist = new List<int[]>[n];         for (int i = 0; i < n; i++) {             adjlist[i] = new List<int[]>();         }                  // Initialize a queue to perform BFS         Queue<int[]> q = new Queue<int[]>();          Dictionary<int, int> mp = new Dictionary<int, int>();          // Store the maximum distance of         // every node from source vertex         int ans = -1000000000;          // Initialize adjacency list         for (int i = 0; i < edges.Length; i++) {             int[] edge = edges[i];             adjlist[edge[0]].Add(new int[] {edge[1], edge[2]});         }          // Push the first element into queue         q.Enqueue(new int[] {src, 0});          int level = 0;          // Iterate until the queue becomes empty         // and the number of nodes between src         // and dst vertex is at most to K         while (q.Count > 0 && level < K + 2) {              // Current size of the queue             int sz = q.Count;              for (int i = 0; i < sz; i++) {                  // Extract the front                 // element of the queue                 int[] pr = q.Dequeue();                  // If the dst vertex is reached                 if (pr[0] == dst) {                     ans = Math.Max(ans, pr[1]);                 }                  // Traverse the adjacent nodes                 foreach (int[] pr2 in adjlist[pr[0]]) {                      // If the distance is greater                     // than the current distance                     if (!mp.ContainsKey(pr2[0]) || mp[pr2[0]] > pr[1] + pr2[1]) {                         // Push it into the queue                         q.Enqueue(new int[] {pr2[0], pr[1] + pr2[1]});                         mp[pr2[0]] = pr[1] + pr2[1];                     }                 }             }              // Increment the level by 1             level++;         }          // Finally, return the maximum distance         return ans != -1000000000 ? ans : -1;     }      // Driver Code     public static void Main()     {         int n = 3, src = 0, dst = 2, k = 1;          int[][] edges = new int[][] {             new int[] {0, 1, 100},             new int[] {1, 2, 100},             new int[] {0, 2, 500}         };          Console.WriteLine(FindShortestPath(n, edges, src, dst, k));     } }   // This code is contributed by codebraxnzt 
JavaScript
// JavaScript implementation of the above C++ code  function findShortestPath(n, edges, src, dst, k) {     // Initialize the adjacency list     var adjlist = new Array(n).fill(null).map(() => []);      // Initialize a queue to perform BFS     var q = [];      var mp = new Map();      // Store the maximum distance of     // every node from source vertex     var ans = Number.MIN_SAFE_INTEGER;      // Initialize adjacency list     for (var i = 0; i < edges.length; i++) {         var edge = edges[i];         adjlist[edge[0]].push([edge[1], edge[2]]);     }      // Push the first element into queue     q.push([src, 0]);      var level = 0;      // Iterate until the queue becomes empty     // and the number of nodes between src     // and dst vertex is at most to K     while (q.length > 0 && level < k + 2) {         // Current size of the queue         var sz = q.length;          for (var i = 0; i < sz; i++) {             // Extract the front             // element of the queue             var pr = q.shift();              // If the dst vertex is reached             if (pr[0] === dst) {                 ans = Math.max(ans, pr[1]);             }              // Traverse the adjacent nodes             for (var j = 0; j < adjlist[pr[0]].length; j++) {                 var pr2 = adjlist[pr[0]][j];                  // If the distance is greater                 // than the current distance                 if (mp.get(pr2[0]) === undefined || mp.get(pr2[0]) > pr[1] + pr2[1]) {                     // Push it into the queue                     q.push([pr2[0], pr[1] + pr2[1]]);                     mp.set(pr2[0], pr[1] + pr2[1]);                 }             }         }          // Increment the level by 1         level++;     }      // Finally, return the maximum distance     return ans !== Number.MIN_SAFE_INTEGER ? ans : -1; }  // Example usage var n = 3, src = 0, dst = 2, k = 1; var edges = [[0, 1, 100], [1, 2, 100], [0, 2, 500]];  console.log(findShortestPath(n, edges, src, dst, k)); 

Output
500

Time Complexity: O(N + E)
Auxiliary Space: O(N)

Alternate approach: Modification of Bellman Ford algorithm after modifying the weights

If all the weights of the given graph are made negative of the original weights, the path taken to minimize the sum of weights with at most k nodes in middle will give us the path we need. Hence this question is similar to this problem. Below is the code implementation of the problem

C++
#include <bits/stdc++.h> using namespace std;  int max_cost(int n, vector<vector<int> >& edges, int src,              int dst, int k) {     // We use 2 arrays for this algorithm     // temp is the shortest distances array in current pass     vector<int> temp(n, INT_MAX);     temp[src] = 0;     for (int i = 0; i <= k; i++) {         // c is the shortest distances array in previous         // pass For every iteration current pass becomes the         // previous         vector<int> c(temp);         for (auto edge : edges) {             int a = edge[0], b = edge[1], d = edge[2];             // Updating the current array using previous             // array Subtracting d is same as adding -d             temp[b]                 = min(temp[b],                       c[a] == INT_MAX ? INT_MAX : c[a] - d);         }     }     // Checking is dst is reachable from src or not     if (temp[dst] != INT_MAX) {         // Returning the negative value of the shortest         // distance to return the longest distance         return -temp[dst];     }     return -1; }  int main() {     vector<vector<int> > edges = {         { 0, 1, 100 },         { 1, 2, 100 },         { 0, 2, 500 },     };     int src = 0;     int dst = 2;     int k = 1;     int n = 3;      cout << max_cost(n, edges, src, dst, k) << endl;     return 0; } // This code was contributed Prajwal Kandekar 
Java
import java.util.*;  public class Main {     static int max_cost(int n, List<List<Integer>> edges, int src,              int dst, int k)     {                // We use 2 arrays for this algorithm         // temp is the shortest distances array in current pass         int[] temp = new int[n];         Arrays.fill(temp, Integer.MAX_VALUE);         temp[src] = 0;         for (int i = 0; i <= k; i++)          {                        // c is the shortest distances array in previous             // pass For every iteration current pass becomes the             // previous             int[] c = temp.clone();             for (List<Integer> edge : edges) {                 int a = edge.get(0), b = edge.get(1), d = edge.get(2);                                // Updating the current array using previous                 // array Subtracting d is same as adding -d                 temp[b] = Math.min(temp[b], c[a] == Integer.MAX_VALUE ? Integer.MAX_VALUE : c[a] - d);             }         }                // Checking if dst is reachable from src or not         if (temp[dst] != Integer.MAX_VALUE)         {                        // Returning the negative value of the shortest             // distance to return the longest distance             return -temp[dst];         }         return -1;     }      public static void main(String[] args) {         List<List<Integer>> edges = Arrays.asList(             Arrays.asList(0, 1, 100),             Arrays.asList(1, 2, 100),             Arrays.asList(0, 2, 500)         );         int src = 0;         int dst = 2;         int k = 1;         int n = 3;          System.out.println(max_cost(n, edges, src, dst, k));     } } 
Python
def max_cost(n, edges, src, dst, k):       # We use 2 arrays for this algorithm     # temp is the shortest distances array in current pass     temp=[0 if i==src else float("inf") for i in range(n)]     for _ in range(k+1):           # c is the shortest distances array in previous pass         # For every iteration current pass becomes the previous         c=temp.copy()         for a,b,d in edges:               # Updating the current array using previous array             # Subtracting d is same as adding -d             temp[b]=min(temp[b],c[a]-d)     # Checking is dst is reachable from src or not     if temp[dst]!=float("inf"):           # Returning the negative value of the shortest distance to return the longest distance         return -temp[dst]     return -1    edges = [     [0, 1, 100],     [1, 2, 100],     [0, 2, 500], ]  src = 0 dst = 2 k = 1 n = 3      print(max_cost(n,edges,src,dst,k))  # This code was contributed by Akshayan Muralikrishnan 
C#
using System; using System.Collections.Generic; using System.Linq;  public class MainClass {     static int MaxCost(int n, List<List<int>> edges, int src, int dst, int k)     {          // We use 2 arrays for this algorithm         // temp is the shortest distances array in current pass         int[] temp = new int[n];         Array.Fill(temp, int.MaxValue);         temp[src] = 0;         for (int i = 0; i <= k; i++)         {              // c is the shortest distances array in previous             // pass For every iteration current pass becomes the             // previous             int[] c = (int[])temp.Clone();             foreach (var edge in edges)             {                 int a = edge[0], b = edge[1], d = edge[2];                  // Updating the current array using previous                 // array Subtracting d is same as adding -d                 temp[b] = Math.Min(temp[b], c[a] == int.MaxValue ? int.MaxValue : c[a] - d);             }         }          // Checking if dst is reachable from src or not         if (temp[dst] != int.MaxValue)         {              // Returning the negative value of the shortest             // distance to return the longest distance             return -temp[dst];         }         return -1;     }      public static void Main()     {         List<List<int>> edges = new List<List<int>>()         {             new List<int>(){0, 1, 100},             new List<int>(){1, 2, 100},             new List<int>(){0, 2, 500}         };         int src = 0;         int dst = 2;         int k = 1;         int n = 3;          Console.WriteLine(MaxCost(n, edges, src, dst, k));     } } 
JavaScript
function max_cost(n, edges, src, dst, k) {     // We use 2 arrays for this algorithm     // temp is the shortest distances array in current pass     let temp = new Array(n).fill(Number.MAX_SAFE_INTEGER);     temp[src] = 0;      for (let i = 0; i <= k; i++) {         // c is the shortest distances array in previous         // pass For every iteration current pass becomes the         // previous         let c = [...temp];         for (let j = 0; j < edges.length; j++) {             let [a, b, d] = edges[j];             // Updating the current array using previous             // array Subtracting d is same as adding -d             temp[b] = Math.min(temp[b], (c[a] === Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : c[a] - d);         }     }      // Checking is dst is reachable from src or not     if (temp[dst] !== Number.MAX_SAFE_INTEGER) {         // Returning the negative value of the shortest         // distance to return the longest distance         return -temp[dst];     }     return -1; }  let edges = [    [0, 1, 100],     [1, 2, 100],     [0, 2, 500] ]; let src = 0; let dst = 2; let k = 1; let n = 3;  console.log(max_cost(n, edges, src, dst, k)); 

Output
500

Time Complexity: O(E*k) where E is the number of edges
Auxiliary Space: O(n)



Next Article
Shortest distance between two cells in a matrix or grid

R

rutvikchandla3
Improve
Article Tags :
  • DSA
  • Graph
  • Hash
  • Queue
  • BFS
  • Graph Traversals
Practice Tags :
  • BFS
  • Graph
  • Hash
  • Queue

Similar Reads

  • Queue Data Structure
    A Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
    2 min read
  • Introduction to Queue Data Structure
    Queue is a linear data structure that follows FIFO (First In First Out) Principle, so the first element inserted is the first to be popped out. FIFO Principle in Queue: FIFO Principle states that the first element added to the Queue will be the first one to be removed or processed. So, Queue is like
    5 min read
  • Introduction and Array Implementation of Queue
    Similar to Stack, Queue is a linear data structure that follows a particular order in which the operations are performed for storing data. The order is First In First Out (FIFO). One can imagine a queue as a line of people waiting to receive something in sequential order which starts from the beginn
    2 min read
  • Queue - Linked List Implementation
    In this article, the Linked List implementation of the queue data structure is discussed and implemented. Print '-1' if the queue is empty. Approach: To solve the problem follow the below idea: we maintain two pointers, front and rear. The front points to the first item of the queue and rear points
    8 min read
  • Applications, Advantages and Disadvantages of Queue
    A Queue is a linear data structure. This data structure follows a particular order in which the operations are performed. The order is First In First Out (FIFO). It means that the element that is inserted first in the queue will come out first and the element that is inserted last will come out last
    5 min read
  • Different Types of Queues and its Applications
    Introduction : A Queue is a linear structure that follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. In this article, the diff
    8 min read
  • Queue implementation in different languages

    • Queue in C++ STL
      In C++, queue container follows the FIFO (First In First Out) order of insertion and deletion. According to it, the elements that are inserted first should be removed first. This is possible by inserting elements at one end (called back) and deleting them from the other end (called front) of the dat
      5 min read

    • Queue Interface In Java
      The Queue Interface is a part of java.util package and extends the Collection interface. It stores and processes the data in order means elements are inserted at the end and removed from the front. Key Features: Most implementations, like PriorityQueue, do not allow null elements.Implementation Clas
      12 min read

    • Queue in Python
      Like a stack, the queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first.  Operations
      6 min read

    • C# Queue with Examples
      A Queue in C# is a collection that follows the First-In-First-Out (FIFO) principle which means elements are processed in the same order they are added. It is a part of the System.Collections namespace for non-generic queues and System.Collections.Generic namespace for generic queues. Key Features: F
      6 min read

    • Implementation of Queue in Javascript
      A Queue is a linear data structure that follows the FIFO (First In, First Out) principle. Elements are inserted at the rear and removed from the front. Queue Operationsenqueue(item) - Adds an element to the end of the queue.dequeue() - Removes and returns the first element from the queue.peek() - Re
      7 min read

    • Queue in Go Language
      A queue is a linear structure that follows a particular order in which the operations are performed. The order is First In First Out (FIFO). Now if you are familiar with other programming languages like C++, Java, and Python then there are inbuilt queue libraries that can be used for the implementat
      4 min read

    • Queue in Scala
      A queue is a first-in, first-out (FIFO) data structure. Scala offers both an immutable queue and a mutable queue. A mutable queue can be updated or extended in place. It means one can change, add, or remove elements of a queue as a side effect. Immutable queue, by contrast, never change. In Scala, Q
      3 min read

    Some question related to Queue implementation

    • Implementation of Deque using doubly linked list
      A Deque (Double-Ended Queue) is a data structure that allows adding and removing elements from both the front and rear ends. Using a doubly linked list to implement a deque makes these operations very efficient, as each node in the list has pointers to both the previous and next nodes. This means we
      9 min read

    • Queue using Stacks
      Given a stack that supports push and pop operations, your task is to implement a queue using one or more instances of that stack along with its operations. Table of Content By Making Enqueue Operation CostlyBy Making Dequeue Operation Costly Queue Implementation Using One Stack and RecursionBy Makin
      11 min read

    • implement k Queues in a single array
      Given an array of size n, the task is to implement k queues using the array. enqueue(qn, x) : Adds the element x into the queue number qn dequeue(qn, x) : Removes the front element from queue number qn isFull(qn) : Checks if the queue number qn is fullisEmpty(qn) : Checks if the queue number qn is e
      15+ min read

    • LRU Cache - Complete Tutorial
      What is LRU Cache? Cache replacement algorithms are efficiently designed to replace the cache when the space is full. The Least Recently Used (LRU) is one of those algorithms. As the name suggests when the cache memory is full, LRU picks the data that is least recently used and removes it in order t
      8 min read

    Easy problems on Queue

    • Detect cycle in an undirected graph using BFS
      Given an undirected graph, the task is to determine if cycle is present in it or not. Examples: Input: V = 5, edges[][] = [[0, 1], [0, 2], [0, 3], [1, 2], [3, 4]] Output: trueExplanation: The diagram clearly shows a cycle 0 → 2 → 1 → 0. Input: V = 4, edges[][] = [[0, 1], [1, 2], [2, 3]] Output: fals
      6 min read

    • Breadth First Search or BFS for a Graph
      Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
      15+ min read

    • Traversing directory in Java using BFS
      Given a directory, print all files and folders present in directory tree rooted with given directory. We can iteratively traverse directory in BFS using below steps. We create an empty queue and we first enqueue given directory path. We run a loop while queue is not empty. We dequeue an item from qu
      2 min read

    • Vertical Traversal of a Binary Tree
      Given a Binary Tree, the task is to find its vertical traversal starting from the leftmost level to the rightmost level. If multiple nodes pass through a vertical line, they should be printed as they appear in the level order traversal of the tree. Examples: Input: Output: [[4], [2], [1, 5, 6], [3,
      10 min read

    • Print Right View of a Binary Tree
      Given a Binary Tree, the task is to print the Right view of it. The right view of a Binary Tree is a set of rightmost nodes for every level. Examples: Example 1: The Green colored nodes (1, 3, 5) represents the Right view in the below Binary tree. Example 2: The Green colored nodes (1, 3, 4, 5) repr
      15+ min read

    • Find Minimum Depth of a Binary Tree
      Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. For example, minimum depth of below Binary Tree is 2. Note that the path must end on a leaf node. For example, the minimum depth of below Bi
      15 min read

    • Check whether a given graph is Bipartite or not
      Given a graph with V vertices numbered from 0 to V-1 and a list of edges, determine whether the graph is bipartite or not. Note: A bipartite graph is a type of graph where the set of vertices can be divided into two disjoint sets, say U and V, such that every edge connects a vertex in U to a vertex
      9 min read

    Intermediate problems on Queue

    • Flatten a multilevel linked list using level order traversal
      Given a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate list. These child lists may have one or more children of their own to produce a multilevel linked list. Given the head of the first level of the list. The task is to fla
      9 min read

    • Level with maximum number of nodes
      Given a binary tree, the task is to find the level in a binary tree that has the maximum number of nodes. Note: The root is at level 0. Examples: Input: Binary Tree Output : 2Explanation: Input: Binary tree Output:1Explanation Using Breadth First Search - O(n) time and O(n) spaceThe idea is to trave
      12 min read

    • Find if there is a path between two vertices in a directed graph
      Given a Directed Graph and two vertices in it, check whether there is a path from the first given vertex to second. Example: Consider the following Graph: Input : (u, v) = (1, 3) Output: Yes Explanation: There is a path from 1 to 3, 1 -> 2 -> 3 Input : (u, v) = (3, 6) Output: No Explanation: T
      15 min read

    • Print all nodes between two given levels in Binary Tree
      Given a binary tree, print all nodes between two given levels in a binary tree. Print the nodes level-wise, i.e., the nodes for any level should be printed from left to right. In the above tree, if the starting level is 2 and the ending level is 3 then the solution should print: 2 3 4 5 6 7 Note: Le
      15 min read

    • Find next right node of a given key
      Given a Binary tree and a key in the binary tree, find the node right to the given key. If there is no node on right side, then return NULL. Expected time complexity is O(n) where n is the number of nodes in the given binary tree. Example: Input: root = [10 2 6 8 4 N 5] and key = 2Output: 6Explanati
      15+ min read

    • Minimum steps to reach target by a Knight | Set 1
      Given a square chessboard of n x n size, the position of the Knight and the position of a target are given. We need to find out the minimum steps a Knight will take to reach the target position. Examples: Input: knightPosition: (1, 3) , targetPosition: (5, 0) Output: 3Explanation: In above diagram K
      9 min read

    • Islands in a graph using BFS
      Given an n x m grid of 'W' (Water) and 'L' (Land), the task is to count the number of islands. An island is a group of adjacent 'L' cells connected horizontally, vertically, or diagonally, and it is surrounded by water or the grid boundary. The goal is to determine how many distinct islands exist in
      15+ min read

    • Level order traversal line by line (Using One Queue)
      Given a Binary Tree, the task is to print the nodes level-wise, each level on a new line. Example: Input: Output:12 34 5 Table of Content [Expected Approach – 1] Using Queue with delimiter – O(n) Time and O(n) Space[Expected Approach – 2] Using Queue without delimiter – O(n) Time and O(n) Space[Expe
      12 min read

    • First non-repeating character in a stream
      Given an input stream s consisting solely of lowercase letters, you are required to identify which character has appeared only once in the stream up to each point. If there are multiple characters that have appeared only once, return the one that first appeared. If no character has appeared only onc
      15+ min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences