The Wayback Machine - https://web.archive.org/web/20240815062227/https://www.geeksforgeeks.org/find-if-there-is-a-path-of-more-than-k-length-from-a-source/
Open In App

Find if there is a path of more than k length from a source

Last Updated : 10 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a graph, a source vertex in the graph and a number k, find if there is a simple path (without any cycle) starting from given source and ending at any other vertex such that the distance from source to that vertex is atleast ‘k’ length.

Example:

Weighted Undirected Graph

Input  : Source s = 0, k = 58
Output : True
There exists a simple path 0 -> 7 -> 1
-> 2 -> 8 -> 6 -> 5 -> 3 -> 4
Which has a total distance of 60 km which
is more than 58.

Input  : Source s = 0, k = 62
Output : False

In the above graph, the longest simple
path has distance 61 (0 -> 7 -> 1-> 2
 -> 3 -> 4 -> 5-> 6 -> 8, so output 
should be false for any input greater 
than 61.

We strongly recommend you to minimize your browser and try this yourself first.

One important thing to note is, simply doing BFS or DFS and picking the longest edge at every step would not work. The reason is, a shorter edge can produce longer path due to higher weight edges connected through it.

The idea is to use Backtracking. We start from given source, explore all paths from current vertex. We keep track of current distance from source. If distance becomes more than k, we return true. If a path doesn’t produces more than k distance, we backtrack.

How do we make sure that the path is simple and we don’t loop in a cycle? The idea is to keep track of current path vertices in an array. Whenever we add a vertex to path, we check if it already exists or not in current path. If it exists, we ignore the edge.

Below is implementation of above idea. 

Java




// Java Program to find if there is a simple path with
// weight more than k
import java.util.*;
public class GFG{
 
  static class AdjListNode {
    int v;
    int weight;
 
    AdjListNode(int _v, int _w)
    {
      v = _v;
      weight = _w;
    }
    int getV() { return v; }
    int getWeight() { return weight; }
  }
 
  // This class represents a dipathted graph using
  // adjacency list representation
  static class Graph
  {
    int V; // No. of vertices
 
    // In a weighted graph, we need to store vertex
    // and weight pair for every edge
    ArrayList<ArrayList<AdjListNode>> adj;
 
    // Allocates memory for adjacency list
    Graph(int V)
    {
      this.V = V;
      adj = new ArrayList<ArrayList<AdjListNode>>(V);
 
      for(int i = 0; i < V; i++)
      {
        adj.add(new ArrayList<AdjListNode>());
      }
    }
 
    // Utility function to an edge (u, v) of weight w
    void addEdge(int u, int v, int weight)
    {
      AdjListNode node1 = new AdjListNode(v, weight);
      adj.get(u).add(node1); // Add v to u's list
 
      AdjListNode node2 = new AdjListNode(u, weight);
      adj.get(v).add(node2); // Add u to v's list
    }
 
    // Returns true if graph has path more than k length
    boolean pathMoreThanK(int src, int k)
    {
       
      // Create a path array with nothing included
      // in path
      boolean path[] = new boolean[V];
 
      Arrays.fill(path, false);
 
      // Add source vertex to path
      path[src] = true;
 
      return pathMoreThanKUtil(src, k, path);
    }
 
    // Prints shortest paths from src to all other vertices
    boolean pathMoreThanKUtil(int src, int k, boolean[] path)
    { 
       
      // If k is 0 or negative, return true;
      if (k <= 0)
        return true;
 
      // Get all adjacent vertices of source vertex src and
      // recursively explore all paths from src.
      ArrayList<AdjListNode> it = adj.get(src);
 
      int index = 0;
      for(int i = 0; i < adj.get(src).size(); i++)
      {
        AdjListNode vertex = adj.get(src).get(i);
 
        // Get adjacent vertex and weight of edge
        int v = vertex.v;
        int w = vertex.weight;
 
        // increase theindex
        index++;
 
        // If vertex v is already there in path, then
        // there is a cycle (we ignore this edge)
        if (path[v] == true)
          continue;
 
        // If weight of is more than k, return true
        if (w >= k)
          return true;
 
        // Else add this vertex to path
        path[v] = true;
 
        // If this adjacent can provide a path longer
        // than k, return true.
        if (pathMoreThanKUtil(v, k-w, path))
          return true;
 
        // Backtrack
        path[v] = false;
      }
 
      // If no adjacent could produce longer path, return
      // false
      return false;
    }
 
  }
 
  // Driver program to test methods of graph class
  public static void main(String[] args)
  {
     
    // create the graph given in above figure
    int V = 9;
    Graph g = new Graph(V);
 
    // making above shown graph
    g.addEdge(0, 1, 4);
    g.addEdge(0, 7, 8);
    g.addEdge(1, 2, 8);
    g.addEdge(1, 7, 11);
    g.addEdge(2, 3, 7);
    g.addEdge(2, 8, 2);
    g.addEdge(2, 5, 4);
    g.addEdge(3, 4, 9);
    g.addEdge(3, 5, 14);
    g.addEdge(4, 5, 10);
    g.addEdge(5, 6, 2);
    g.addEdge(6, 7, 1);
    g.addEdge(6, 8, 6);
    g.addEdge(7, 8, 7);
 
    int src = 0;
    int k = 62;
 
    if(g.pathMoreThanK(src, k))
      System.out.println("YES");
    else
      System.out.println("NO");
 
 
    k = 60;
    if(g.pathMoreThanK(src, k))
      System.out.println("YES");
    else
      System.out.println("NO");
 
  }
}
 
// This code is contributed by adityapande88.


Python3




# Program to find if there is a simple path with
# weight more than k
   
# This class represents a dipathted graph using
# adjacency list representation
class Graph:
    # Allocates memory for adjacency list
    def __init__(self, V):
        self.V = V
        self.adj = [[] for i in range(V)]
   
    # Returns true if graph has path more than k length
    def pathMoreThanK(self,src, k):
        # Create a path array with nothing included
        # in path
        path = [False]*self.V
       
        # Add source vertex to path
        path[src] = 1
       
        return self.pathMoreThanKUtil(src, k, path)
       
    # Prints shortest paths from src to all other vertices
    def pathMoreThanKUtil(self,src, k, path):
        # If k is 0 or negative, return true
        if (k <= 0):
            return True
       
        # Get all adjacent vertices of source vertex src and
        # recursively explore all paths from src.
        i = 0
        while i != len(self.adj[src]):
            # Get adjacent vertex and weight of edge
            v = self.adj[src][i][0]
            w = self.adj[src][i][1]
            i += 1
       
            # If vertex v is already there in path, then
            # there is a cycle (we ignore this edge)
            if (path[v] == True):
                continue
       
            # If weight of is more than k, return true
            if (w >= k):
                return True
       
            # Else add this vertex to path
            path[v] = True
       
            # If this adjacent can provide a path longer
            # than k, return true.
            if (self.pathMoreThanKUtil(v, k-w, path)):
                return True
       
            # Backtrack
            path[v] = False
       
        # If no adjacent could produce longer path, return
        # false
        return False
      
    # Utility function to an edge (u, v) of weight w
    def addEdge(self,u, v, w):
        self.adj[u].append([v, w])
        self.adj[v].append([u, w])
   
# Driver program to test methods of graph class
if __name__ == '__main__':
  
    # create the graph given in above figure
    V = 9
    g = Graph(V)
   
    #  making above shown graph
    g.addEdge(0, 1, 4)
    g.addEdge(0, 7, 8)
    g.addEdge(1, 2, 8)
    g.addEdge(1, 7, 11)
    g.addEdge(2, 3, 7)
    g.addEdge(2, 8, 2)
    g.addEdge(2, 5, 4)
    g.addEdge(3, 4, 9)
    g.addEdge(3, 5, 14)
    g.addEdge(4, 5, 10)
    g.addEdge(5, 6, 2)
    g.addEdge(6, 7, 1)
    g.addEdge(6, 8, 6)
    g.addEdge(7, 8, 7)
   
    src = 0
    k = 62
    if g.pathMoreThanK(src, k):
        print("Yes")
    else:
        print("No")
   
    k = 60
    if g.pathMoreThanK(src, k):
        print("Yes")
    else:
        print("No")


C#




// C# Program to find if there is a simple path with
// weight more than k
using System;
using System.Collections.Generic;
 
class Program
{
 
  // Driver program to test methods of graph class
  static void Main(string[] args)
  {
 
    // create the graph given in above figure
    int V = 9;
    Graph g = new Graph(V);
 
    // making above shown graph
    g.addEdge(0, 1, 4);
    g.addEdge(0, 7, 8);
    g.addEdge(1, 2, 8);
    g.addEdge(1, 7, 11);
    g.addEdge(2, 3, 7);
    g.addEdge(2, 8, 2);
    g.addEdge(2, 5, 4);
    g.addEdge(3, 4, 9);
    g.addEdge(3, 5, 14);
    g.addEdge(4, 5, 10);
    g.addEdge(5, 6, 2);
    g.addEdge(6, 7, 1);
    g.addEdge(6, 8, 6);
    g.addEdge(7, 8, 7);
 
    int src = 0;
    int k = 62;
 
    if (g.pathMoreThanK(src, k))
      Console.WriteLine("YES");
    else
      Console.WriteLine("NO");
 
    k = 60;
    if (g.pathMoreThanK(src, k))
      Console.WriteLine("YES");
    else
      Console.WriteLine("NO");
  }
}
 
class AdjListNode {
  public int v;
  public int weight;
 
  public AdjListNode(int _v, int _w)
  {
    v = _v;
    weight = _w;
  }
  public int getV() { return v; }
  public int getWeight() { return weight; }
}
 
// This class represents a dipathted graph using
// adjacency list representation
class Graph {
  public int V; // No. of vertices
 
  // In a weighted graph, we need to store vertex
  // and weight pair for every edge
  public List<List<AdjListNode> > adj
    = new List<List<AdjListNode> >();
 
  // Allocates memory for adjacency list
  public Graph(int V)
  {
    this.V = V;
    for (int i = 0; i < V; i++)
      adj.Add(new List<AdjListNode>());
  }
 
  // Utility function to an edge (u, v) of weight w
  public void addEdge(int u, int v, int weight)
  {
    AdjListNode node1 = new AdjListNode(v, weight);
    adj[u].Add(node1); // Add v to u's list
 
    AdjListNode node2 = new AdjListNode(u, weight);
    adj[v].Add(node2); // Add u to v's list
  }
 
  // Prints shortest paths from src to all other vertices
  bool pathMoreThanKUtil(int src, int k, bool[] path)
  {
    // If k is 0 or negative, return true;
    if (k <= 0)
      return true;
 
    // Get all adjacent vertices of source vertex src
    // and recursively explore all paths from src.
    List<AdjListNode> it = adj[src];
 
    for (int i = 0; i < adj[src].Count; i++) {
      AdjListNode vertex = adj[src][i];
 
      // Get adjacent vertex and weight of edge
      int v = vertex.v;
      int w = vertex.weight;
 
      // If vertex v is already there in path, then
      // there is a cycle (we ignore this edge)
      if (path[v] == true)
        continue;
 
      // If weight of is more than k, return true
      if (w >= k)
        return true;
 
      // Else add this vertex to path
      path[v] = true;
 
      // If this adjacent can provide a path longer
      // than k, return true.
      if (pathMoreThanKUtil(v, k - w, path))
        return true;
 
      // Backtrack
      path[v] = false;
    }
 
    // If no adjacent could produce longer path, return
    // false
    return false;
  }
 
  // Returns true if graph has path more than k length
  public bool pathMoreThanK(int src, int k)
  {
    // Create a path array with nothing included
    // in path
    bool[] path = new bool[V];
 
    for (int i = 0; i < V; i++)
      path[i] = false;
 
    // Add source vertex to path
    path[src] = true;
    return pathMoreThanKUtil(src, k, path);
  }
}
 
// This code is contributed by Tapesh (tapeshdua420)


Javascript




// JavaScript Program to find if there is a simple path with
// weight more than k
class AdjListNode {
    constructor(v, weight) {
        this.v = v;
        this.weight = weight;
    }
}
 
// This class represents a dipathted graph using
// adjacency list representation
class Graph {
    // Allocates memory for adjacency list
    constructor(V) {
        this.V = V; // No. of vertices
 
        // In a weighted graph, we need to store vertex
        // and weight pair for every edge
        this.adj = [];
        for (var i = 0; i < V; i++) {
            this.adj[i] = [];
        }
    }
 
    // Utility function to an edge (u, v) of weight w
    addEdge(u, v, weight) {
        var node1 = new AdjListNode(v, weight);
        this.adj[u].push(node1); // Add v to u's list
        var node2 = new AdjListNode(u, weight);
        this.adj[v].push(node2); // Add u to v's list
    }
 
    // Prints shortest paths from src to all other vertices
    pathMoreThanKUtil(src, k, path) {
 
        // If k is 0 or negative, return true;
        if (k <= 0)
            return true;
 
        // Get all adjacent vertices of source vertex src and
        // recursively explore all paths from src.
        var it = this.adj[src];
 
        for (var i = 0; i < this.adj[src].length; i++) {
            var vertex = this.adj[src][i];
 
            // Get adjacent vertex and weight of edge
            var v = vertex.v;
            var w = vertex.weight;
 
            // If vertex v is already there in path, then
            // there is a cycle (we ignore this edge)
            if (path[v] == true)
                continue;
 
            // If weight of is more than k, return true
            if (w >= k)
                return true;
 
            // Else add this vertex to path
            path[v] = true;
 
            // If this adjacent can provide a path longer
            // than k, return true.
            if (this.pathMoreThanKUtil(v, k - w, path))
                return true;
 
            // Backtrack
            path[v] = false;
        }
        // If no adjacent could produce longer path, return
        // false
        return false;
    }
 
    // Returns true if graph has path more than k length
    pathMoreThanK(src, k) {
        // Create a path array with nothing included
        // in path
        var path = new Array(V);
        for (var i = 0; i < V; i++) {
            path[i] = false;
        }
        // Add source vertex to path
        path[src] = true;
        return this.pathMoreThanKUtil(src, k, path);
    }
}
 
// Driver program to test methods of graph class
 
// create the graph given in above figure
var V = 9;
var g = new Graph(V);
 
// making above shown graph
g.addEdge(0, 1, 4);
g.addEdge(0, 7, 8);
g.addEdge(1, 2, 8);
g.addEdge(1, 7, 11);
g.addEdge(2, 3, 7);
g.addEdge(2, 8, 2);
g.addEdge(2, 5, 4);
g.addEdge(3, 4, 9);
g.addEdge(3, 5, 14);
g.addEdge(4, 5, 10);
g.addEdge(5, 6, 2);
g.addEdge(6, 7, 1);
g.addEdge(6, 8, 6);
g.addEdge(7, 8, 7);
 
var src = 0;
var k = 62;
 
if (g.pathMoreThanK(src, k)) {
    console.log("YES");
} else {
    console.log("NO");
}
 
k = 60
 
if (g.pathMoreThanK(src, k)) {
    console.log("YES");
} else {
    console.log("NO");
}
 
// This code is contributed by Tapesh(tapeshdua420)


C++




// Program to find if there is a simple path with
// weight more than k
#include<bits/stdc++.h>
using namespace std;
 
// iPair ==>  Integer Pair
typedef pair<int, int> iPair;
 
// This class represents a dipathted graph using
// adjacency list representation
class Graph
{
    int V;    // No. of vertices
 
    // In a weighted graph, we need to store vertex
    // and weight pair for every edge
    list< pair<int, int> > *adj;
    bool pathMoreThanKUtil(int src, int k, vector<bool> &path;);
 
public:
    Graph(int V);  // Constructor
 
    // function to add an edge to graph
    void addEdge(int u, int v, int w);
    bool pathMoreThanK(int src, int k);
};
 
// Returns true if graph has path more than k length
bool Graph::pathMoreThanK(int src, int k)
{
    // Create a path array with nothing included
    // in path
    vector<bool> path(V, false);
 
    // Add source vertex to path
    path[src] = 1;
 
    return pathMoreThanKUtil(src, k, path);
}
 
// Prints shortest paths from src to all other vertices
bool Graph::pathMoreThanKUtil(int src, int k, vector<bool> &path;)
{
    // If k is 0 or negative, return true;
    if (k <= 0)
        return true;
 
    // Get all adjacent vertices of source vertex src and
    // recursively explore all paths from src.
    list<iPair>::iterator i;
    for (i = adj[src].begin(); i != adj[src].end(); ++i)
    {
        // Get adjacent vertex and weight of edge
        int v = (*i).first;
        int w = (*i).second;
 
        // If vertex v is already there in path, then
        // there is a cycle (we ignore this edge)
        if (path[v] == true)
            continue;
 
        // If weight of is more than k, return true
        if (w >= k)
            return true;
 
        // Else add this vertex to path
        path[v] = true;
 
        // If this adjacent can provide a path longer
        // than k, return true.
        if (pathMoreThanKUtil(v, k-w, path))
            return true;
 
        // Backtrack
        path[v] = false;
    }
 
    // If no adjacent could produce longer path, return
    // false
    return false;
}
 
// Allocates memory for adjacency list
Graph::Graph(int V)
{
    this->V = V;
    adj = new list<iPair> [V];
}
 
// Utility function to an edge (u, v) of weight w
void Graph::addEdge(int u, int v, int w)
{
    adj[u].push_back(make_pair(v, w));
    adj[v].push_back(make_pair(u, w));
}
 
// Driver program to test methods of graph class
int main()
{
    // create the graph given in above figure
    int V = 9;
    Graph g(V);
 
    //  making above shown graph
    g.addEdge(0, 1, 4);
    g.addEdge(0, 7, 8);
    g.addEdge(1, 2, 8);
    g.addEdge(1, 7, 11);
    g.addEdge(2, 3, 7);
    g.addEdge(2, 8, 2);
    g.addEdge(2, 5, 4);
    g.addEdge(3, 4, 9);
    g.addEdge(3, 5, 14);
    g.addEdge(4, 5, 10);
    g.addEdge(5, 6, 2);
    g.addEdge(6, 7, 1);
    g.addEdge(6, 8, 6);
    g.addEdge(7, 8, 7);
 
    int src = 0;
    int k = 62;
    g.pathMoreThanK(src, k)? cout << "Yes\n" :
                             cout << "No\n";
 
    k = 60;
    g.pathMoreThanK(src, k)? cout << "Yes\n" :
                             cout << "No\n";
 
    return 0;
}


Output: 
 

No
Yes

Exercise: 
Modify the above solution to find weight of longest path from a given source.

Time Complexity: The time complexity of this algorithm is O((V-1)!) where V is the number of vertices.

Auxiliary Space: O(V)

Explanation: 

From the source node, we one-by-one visit all the paths and check if the total weight is greater than k for each path. So, the worst case will be when the number of possible paths is maximum. This is the case when every node is connected to every other node. 

Since the starting point is fixed, we need to find a path including all the other vertices. There can be (V-1) choices for the second node, (V-2) choices for the third node, and so on till, 1 choice for the last node.

Therefore the total number of possible paths are (V-1)! in the worst case.

In the recursive call, when we reach a node, we again do recursive call for all of its child. Changing the state of array(which stores whether the node is visited or not), takes O(1) time.

So the time complexity becomes O((V-1)!).

The explanation for time complexity is contributed by Pranav Nambiar, and Aayush Patel.



Previous Article
Next Article

Similar Reads

Length of longest subarray in which elements greater than K are more than elements not greater than K
Given an array arr[] of length N. The task is to find the length of the longest subarray in which there are more greater (than a given number K) elements than elements less than or equal to K.Examples: Input : N = 5, K = 2, arr[]={ 1, 2, 3, 4, 1 } Output : 3 The subarray [2, 3, 4] or [3, 4, 1] satisfy the given condition, and there is no subarray o
3 min read
Convert the undirected graph into directed graph such that there is no path of length greater than 1
Given an undirected graph with N vertices and M edges and no self loops or multiple edges. The task is to convert the given undirected graph into a directed graph such that there is no path of length greater than 1. If it is possible to make such a graph then print two space-separated integers u and v in M lines where u, v denotes source and destin
10 min read
Generate all binary permutations such that there are more or equal 1's than 0's before every point in all permutations
Generate all permutations of a given length such that every permutation has more or equals 1's than 0's in all prefixes of the permutation. Examples: Input: len = 4 Output: 1111 1110 1101 1100 1011 1010 Note that a permutation like 0101 can not be in output because there are more 0's from index 0 to 2 in this permutation. Input: len = 3 Output: 111
5 min read
Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
Given a connected graph with N vertices and M edges. The task is to find the shortest path from source to the destination vertex such that the difference between adjacent edge weights in the shortest path change from positive to negative and vice versa ( Weight(E1) &gt; Weight(E2) &lt; Weight(E3) .... ). If no such path exists then print -1. Exampl
13 min read
For each A[i] find smallest subset with all elements less than A[i] sum more than B[i]
Given two arrays A[] and B[] of N integers, the task is to find for each element A[i], the size of the smallest subset S of indices, such that : Each value corresponding to the indices in subset S is strictly less than A[i].Sum of elements corresponding to the indices in B is strictly greater than B[i]. Examples: Input: N = 5, A = {3, 2, 100, 4, 5}
10 min read
Count number of binary strings such that there is no substring of length greater than or equal to 3 with all 1's
Given an integer N, the task is to count the number of binary strings possible of length N such that they don't contain "111" as a substring. The answer could be large so print answer modulo 109 + 7.Examples: Input: N = 3 Output: 7 All possible substring are "000", "001", "010", "011", "100", "101" and "110". "111" is not a valid string.Input N = 1
6 min read
Check if the frequency of any character is more than half the length of the string
Given a string str, the task is to check if the frequency of any character is more than half the length of the given string. The characters can be lowercase or uppercase alphabets, digits and special characters. Examples: Input: str = "AAa*2AAAA" Output: Yes The frequency of 'A' is more than half the length of the string. Input: str = "abB@2a" Outp
5 min read
Minimum number of removals required such that no subsequence of length 2 occurs more than once
Given a string S consisting of N lowercase characters, the task is to modify the given string such that no subsequence of length two repeats in the string by removing minimum number of characters. Examples: Input: S = "abcaadbcd"Output: abcdExplanation: Removing the characters at indices {2, 3, 4, 5, 6, 7} modifies the string to "abcd", that contai
7 min read
Sequences of given length where every element is more than or equal to twice of previous
Given two integers m &amp; n, find the number of possible sequences of length n such that each of the next element is greater than or equal to twice of the previous element but less than or equal to m. Examples : Input : m = 10, n = 4 Output : 4 There should be n elements and value of last element should be at-most m. The sequences are {1, 2, 4, 8}
13 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 -&gt; 2 -&gt; 3 Input : (u, v) = (3, 6) Output: No Explanation: There is no path from 3 to 6 Approach: Either Bread
15 min read
Find if there is a path between two vertices in a directed graph | Set 2
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 -&gt; 2 -&gt; 3 Input : (u, v) = (3, 6) Output: No Explanation: There is no path from 3 to 6 A BFS or DFS based sol
7 min read
Find if there is a path between two vertices in an undirected graph
Given an undirected graph with N vertices and E edges and two vertices (U, V) from the graph, the task is to detect if a path exists between these two vertices. Print "Yes" if a path exists and "No" otherwise. Examples: U = 1, V = 2 Output: No Explanation: There is no edge between the two points and hence its not possible to reach 2 from 1. Input:
15+ min read
Find whether there is path between two cells in matrix
Given N X N matrix filled with 1, 0, 2, 3. Find whether there is a path possible from source to destination, traversing through blank cells only. You can traverse up, down, right, and left. A value of cell 1 means Source.A value of cell 2 means Destination.A value of cell 3 means Blank cell.A value of cell 0 means Blank Wall.Note: there are an only
15+ min read
Find if there is a pair in root to a leaf path with sum equals to root's data
Given a binary tree, find if there is a pair in root to a leaf path such that sum of values in pair is equal to root's data. For example, in below tree there are no pairs in any root to leaf path with sum equal to root's data. The idea is based on hashing and tree traversal. The idea is similar to method 2 of array pair sum problem. Create an empty
8 min read
Minimum cost to reverse edges such that there is path between every pair of nodes
Given a connected, directional graph. Each node is connected to exactly two other nodes. There is a weight associated with each edge denoting the cost to reverse its direction. The task is to find the minimum cost to reverse some edges of the graph such that it is possible to go from each node to every other node. Examples: Input: 5 1 2 7 5 1 8 5 4
7 min read
Check if there is a root to leaf path with given sequence
Given a binary tree and an array, the task is to find if the given array sequence is present as a root-to-leaf path in given tree. Examples : Input : arr[] = {5, 2, 4, 8} for above tree Output: "Path Exist" Input : arr[] = {5, 3, 4, 9} for above tree Output: "Path does not Exist" A simple solution for this problem is to find all root-to-leaf paths
9 min read
Find maximum N such that the sum of square of first N natural numbers is not more than X
Given an integer X, the task is to find the maximum value N such that the sum of first N natural numbers is not more than X. Examples: Input: X = 5 Output: 2 2 is the maximum possible value of N because for N = 3, the sum of the series will exceed X i.e. 12 + 22 + 32 = 1 + 4 + 9 = 14 Input: X = 25 Output: 3 Simple Solution: A simple solution is to
12 min read
Find all array elements occurring more than ⌊N/3⌋ times
Given an array arr[] consisting of N integers, the task is to find all the array elements which occurs more than floor (n/3) times. Examples: Input: arr[] = {5, 3, 5}Output: 5Explanation:The frequency of 5 is 2, which is more than N/3(3/3 = 1). Input: arr[] = {7, 7, 7, 3, 4, 4, 4, 5}Output: 4 7Explanation:The frequency of 7 and 4 in the array is 3,
15+ min read
Given Array of size n and a number k, find all elements that appear more than n/k times
Given an array of size n and an integer k, find all elements in the array that appear more than n/k times. Examples: Input: arr[] = {3, 1, 2, 2, 1, 2, 3, 3}, k = 4Output: {2, 3}Explanation: Here n/k is 8/4 = 2, therefore 2 appears 3 times in the array that is greater than 2 and 3 appears 3 times in the array that is greater than 2 Input: arr[] = {9
15+ min read
Minimum cost path from source node to destination node via an intermediate node
Given an undirected weighted graph. The task is to find the minimum cost of the path from source node to the destination node via an intermediate node. Note: If an edge is traveled twice, only once weight is calculated as cost. Examples: Input: source = 0, destination = 2, intermediate = 3; Output: 6 The minimum cost path 0-&gt;1-&gt;3-&gt;1-&gt;2
12 min read
Source to destination in 2-D path with fixed sized jumps
Given the source point and the destination point of the path and two integers x and y. The task is to check whether it is possible to move from source to the destination with the below moves, If current position is (a, b) then the valid moves are: (a + x, b + y)(a - x, b + y)(a + x, b - y)(a - x, b - y) Examples: Input: Sx = 0, Sy = 0, Dx = 0, Dy =
6 min read
Shortest path in a graph from a source S to destination D with exactly K edges for multiple Queries
Given a graph with N nodes, a node S and Q queries each consisting of a node D and K, the task is to find the shortest path consisting of exactly K edges from node S to node D for each query. If no such path exists then print -1. Note: K will always be lesser than 2 * N. Examples: Input: N = 3, edges[][] = {{1, 2, 5}, {2, 3, 3}, {3, 1, 4}}, S = 1,
8 min read
Print path from given Source to Destination in 2-D Plane
Given coordinates of a source point (srcx, srcy) and a destination point (dstx, dsty), the task is to determine the possible path to reach the destination point from source point. From any point (x, y) there only two types of valid moves: (2 * x + y, y) or (x, 2 * y + x). If the path doesn't exist then print -1.Examples: Input: (srcx, srcy) = {5, 8
11 min read
Shortest Path with even number of Edges from Source to Destination
Given an undirected graph G, the task is to find the shortest path of even-length, given 1 as Source Node and N as Destination Node. Path length refers to the number of edges present in a path (not the cost of the path). Examples: Input: N = 5, G is given below: Output: 10 Explanation: All paths from 1(source node) to 5 (destination node) are: 1-
13 min read
Single source shortest path between two cities
Given a graph of N Nodes and E edges in form of {U, V, W} such that there exists an edge between U and V with weight W. You are given an integer K and source src and destination dst. The task is to find the cheapest cost path from given source to destination from K stops.Examples: Input: N = 3, edges = [[0, 1, 100], [1, 2, 100], [0, 2, 500]], src =
15+ min read
Queries to check if a path made up of even numbers from source to destination exists in a Matrix
Given two arrays R[] and C[] consisting of N integers such that a matrix of dimensions N x N can be formed whose element at index (i, j) is given by (R[i] + C[j]) for all possible pairs from the two arrays. Given a matrix Queries[][] with each row representing a query of the type {A, B, X, Y}, the task for each query is to check whether there exist
13 min read
Path from a given source to a given destination having Kth largest weight in a Graph
Given a weighted graph consisting of N nodes and M edges, a source vertex, a destination vertex, and an integer K, the task is to find the path with Kth largest weight from source to destination in the graph. Examples: Input: N = 7, M = 8, source = 0, destination = 6, K = 3, Edges[][] = {{0, 1, 10}, {1, 2, 10}, {2, 3, 10}, {0, 3, 40}, {3, 4, 2}, {4
14 min read
Shortest path from a source cell to a destination cell of a Binary Matrix through cells consisting only of 1s
Given a binary matrix mat[][] of dimensions of N * M and pairs of integers src and dest representing source and destination cells respectively, the task is to find the shortest sequence of moves from the given source cell to the destination cell via cells consisting only of 1s. The allowed moves are moving a cell left (L), right (R), up (U), and do
15+ min read
Minimum cost path from source node to destination node via K intermediate nodes
Given a Graph consisting of N vertices and M weighted edges and an array edges[][], with each row representing the two vertices connected by the edge and the weight of the edge, the task is to find the path with the least sum of weights from a given source vertex src to a given destination vertex dst, made up of K intermediate vertices. If no such
10 min read
Maximum cost path from source node to destination node via at most K intermediate nodes
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 su
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg