VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-if-there-is-a-path-of-more-than-k-length-from-a-source/

⇱ Path of Length Greater Than or Equal to K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Path of Length Greater Than or Equal to K

Last Updated : 19 Jun, 2026

Given an undirected weighted graph with V vertices numbered from 0 to V - 1 and an integer k, find if there exists a simple path starting from vertex 0 whose total path length is greater than or equal to k. A simple path is a path in which no vertex is visited more than once.

Examples:

Input: V = 5, edges[][] = [[0, 1, 4], [0, 2, 8], [1, 4, 6], [2, 3, 2], [4, 3, 10]], k = 8
Output: true
Explanation: One possible simple path is 0 -> 1 -> 4. The total path length is 4 + 6 = 10, which is greater than or equal to k = 8. Hence, a valid path exists and the answer is true.

👁 123456

Input: V = 4 , edges[][] = [[0, 1, 5], [1, 2, 1], [2, 3, 1]], k = 8
Output: false
Explanation: There exists no path which has a distance of 8.

[Expected Approach] Using DFS and Backtracking - O(V!) Time and O(V) Space

We need to determine whether there exists a simple path starting from vertex 0 whose total length is at least k. Since a simple path cannot contain repeated vertices, we can explore all possible paths using DFS while marking visited vertices. As we traverse an edge, we reduce the remaining length required by its weight. If the remaining length becomes non-positive, a valid path has been found. After exploring a path, we backtrack by unmarking the current vertex so that it can be used in other potential paths.

Step By Step Implementation:

  • Build an adjacency list from the given edge list.
  • Create a visited array to avoid revisiting vertices and maintain a simple path.
  • Start DFS from vertex 0 with the required path length k.
  • For every unvisited neighbor, check if its edge weight is enough to satisfy the remaining length.
  • Otherwise, continue DFS with the remaining length reduced by the edge weight.
  • If any DFS call succeeds, return true.
  • Backtrack by unmarking the current vertex after exploring all paths through it.
  • Return false if no valid path is found.

Output
true
Comment
Article Tags: