Cheapest Flights Within K Stops | DFS + Pruning | Leetcode

Sdílet
Vložit
  • čas přidán 13. 06. 2020
  • This video explains a very important graph programming interview problem which is to find the minimum cost path from source to destination.This is a very typical shortest path problem and can be solved by using a variety of algorithms like Dijkstra, Floyd Warshall, Bellman Ford, BFS, DFS with memoization or pruning.In this question, we are allowed to have a maximum of K number of stops from source to destination.This is the only additional constraint.I have shown the simplest approach to solve this problem which is by using DFS + Pruning.I have first explained the intuition and then i have shown the working of the algorithm by taking an example.At the end of the video,i have also shown the code walk through. CODE LINK is present below as usual. If you find any difficulty or have any query then do COMMENT below. PLEASE help our channel by SUBSCRIBING and LIKE our video if you found it helpful...CYA :)
    =================================================================
    INSTAGRAM: / surya.pratap.k
    LinkedIn: / surya-pratap-kahar-47b...
    =================================================================
    CODE LINK: gist.github.com/SuryaPratapK/...
    SIMILAR PROBLEMs:-
    DFS: • Depth first search | D...
    BFS: • Breadth first search |...

Komentáře • 164

  • @tusharrawat1581
    @tusharrawat1581 Před 4 lety +18

    How this solution is going to take just O(n + e) time even in the worst case? Can you explain?

    • @techdose4u
      @techdose4u  Před 4 lety +25

      I forgot to mention that time depends on your sparsity of graph. For dense graph, for finding just 1 path, time is O(V+E) but for sparse graph you can find all paths in the same amortized time. For dense graph, for finding all possible paths, you will have O(V.(V+E)) which can go to V^3 because E=V^2 for dense graph. So, the time for this problem will range from O(N+E) to O(N.(N+E)). This totally got out of mind while explaining. Thanks for this question :)

    • @tusharrawat1581
      @tusharrawat1581 Před 4 lety +3

      @@techdose4u what if we have a complete graph in which all paths from src to dest is at most k stops away, thus DFS is not going to prune on (k < -1), as this condition, would never hit and DFS is also not going to prune on condition (currPrice > minFare) as somehow say, we are getting the minFare cost in decreasing order, thus we are actually going to every single path from src to dst?

    • @techdose4u
      @techdose4u  Před 4 lety +4

      It can't have all paths in decreasing order in a dense graph. Now pruning depends on when you find a path with lower cost. If graph has a special configuration so that your DFS algo (depending on how you made adjacency list) do not prune, then this can only happen when all paths leading to dst are within K stops and all the paths in our DFS are coming in decreasing order of totCost. But this test case will be rare. Also, I mentioned before explaining that this is one of the slowest method (even though it's VE but still it's recursion and not loop).The only optimization is pruning. This works fine if the test case is not designed to make this technique fail. If time complexity is more stringent then try other optimal methods using dynamic programming.

    • @tusharrawat1581
      @tusharrawat1581 Před 4 lety +2

      ​@@techdose4u Got it. Thanks!

    • @techdose4u
      @techdose4u  Před 4 lety +3

      👍

  • @sulekhakumari-hs4gy
    @sulekhakumari-hs4gy Před 4 lety +5

    I am having TechDose regularly as suggested by my frnd and its really making me more efficient coder.

  • @chirag8627
    @chirag8627 Před 3 lety +1

    He sets visited[src] = true so that while exploring some node, you don't visit it again. That can happen if there exist cycle in the graph. But setting it again to false after for loop so that that node can be visited in some other path as he explained in some reply.
    Actually here you can even avoid usage of visited array. Not using visited array in dfs will give you all different paths from source node to any other node. ALL DISTINCT PATH!! As you are pruning here by two constraints that are 1- k(at most k stops) and 2- smaller cost. You will get all the paths that are in bound of these two constraints. And we want one of them that is having smallest cost.
    Hope it helps. @TECH DOSE please correct me if I am wrong anywhere.
    Keep it up!! TECH DOSE, you are helping a lot of people!

  • @techgamer1333
    @techgamer1333 Před 4 lety +18

    Good work, We want more solution like this: Simple Method+ Pruning , I Learned a New things ,Thank you

  • @harshanand4501
    @harshanand4501 Před 3 lety +2

    Thanks for teaching a new concept Pruning with dfs.

  • @GangnamStyle60
    @GangnamStyle60 Před 4 lety +2

    Thanks for the very clear explanation and listing all the possible ways to do it.
    For the DFS + Prunning method, even if we are using a visited array, how is the time complexity still the worst among all other techniques?

  • @vinodhkumar5329
    @vinodhkumar5329 Před rokem

    How can the time complexity id O(n+e) , you are trying all possible paths with pruning optimization and we are visiting the same vertex again in some different path?it seems time complexity will be more than O(n+e)

  • @shivam2kumar988
    @shivam2kumar988 Před 4 lety +3

    I solved it using BFS with the help of heap. Really interesting problem. Thanks for the alternate solution using dfs!

    • @MahirHasancse21
      @MahirHasancse21 Před 4 lety

      Can tell me the full algorithm technique?

    • @crimsoncad3230
      @crimsoncad3230 Před 4 lety

      Did you store the cost of every possible s to d path within 'k' stops in a min-heap and then just returned the 1st element/root of the heap???

  • @rajarai732
    @rajarai732 Před 4 lety +5

    Always makes problem more simple and solve with efficient solution ! Good work :p

  • @double_courage57
    @double_courage57 Před 3 lety

    If DFS explores the longer path first, then pruning will not help. So it should be BFS + pruning as we will encounter the shorter path to destination and later when we explore the longer path, we can use pruning. Can someone please explain???

  • @adhaarsharma753
    @adhaarsharma753 Před 3 lety

    Why does Cost matrix in the code you have provided has the dimensions (n+1,n+1) and not (n,n)?

  • @chirag8627
    @chirag8627 Před 3 lety +6

    TECH DOSE, please make a video on other ways of doing this problem, will help a lot!! Also in many interviews they ask to solve the same problem but with different approaches.

  • @aayush5474
    @aayush5474 Před 3 lety

    why did you take the cost matrix size n+1?

  • @srihari_sh
    @srihari_sh Před 2 lety

    Bro, Do you mouse to write on the black board ?? if any specific app can you tell so that I can use that to explain in my interviews ?

  • @mahi6691
    @mahi6691 Před 2 lety

    Thank you sir!!

  • @mainakmondal5228
    @mainakmondal5228 Před 3 lety

    Awesome explanation...thnx a lot.

  • @kamalakar191
    @kamalakar191 Před 4 lety +2

    Waiting for this!!!!

  • @saurabhgupta4082
    @saurabhgupta4082 Před 3 lety +4

    thank you sir for so awesome content.i just want to make one request to you that please try to make solution videos using other approaches also like dijkstra algo etc.This will help our mind to evolve and we can think of many solutions to a problem whenever interviewer asks us tell approach to solve the questions.once again thank you for doing so much hard work for all of us.

    • @techdose4u
      @techdose4u  Před 3 lety +1

      Yea sure...I am trying to do this.

  • @amruthap6334
    @amruthap6334 Před 4 lety +4

    thank you very much sir awesome content ! i actually wanted to see dijkstra's algo approach as well.. if you have some time please make this solution based on dijkstra algo as well.. ❤❤❤

    • @techdose4u
      @techdose4u  Před 4 lety

      Yea sure. I will explain graph as well :)

  • @idrissadicko9778
    @idrissadicko9778 Před rokem

    Why are you using this line of code ?
    if prices[s] == float("inf"): continue
    is it necessary since you initialize prices[src] = 0 in the begin so in my understanding it can't be infinite again

  • @harshavardhanmadasi1681
    @harshavardhanmadasi1681 Před 2 lety +2

    Iam getting TLE with the above mentioned approach

    • @techdose4u
      @techdose4u  Před 2 lety

      Try to optimize with priority queue code

  • @RohitKumar-ve3fi
    @RohitKumar-ve3fi Před 4 lety +1

    Great explanation!! But did you use prunning in your code.. Like when (totalcost>fare) return;?

    • @techdose4u
      @techdose4u  Před 4 lety +2

      Yes. Inside the for loop in solve, I have checked for totCost > fare.

  • @aastha6911
    @aastha6911 Před 3 lety +1

    Are we trying to explore every possible path in this solution and making optimization by not making further calls in case the number of stops surpasses k or cost of current path becomes more than minCost .

  • @nikhilkamboj4376
    @nikhilkamboj4376 Před 3 lety +1

    HI Tech dose i guess pruning will not work with negative weight
    if we are returning from a particular node just because of value is greater then total max and on next node there is negative value then pruning will fail.
    Not only with this problem but in general graph where positive and negative value present.

  • @ImranAhmed-wd5tr
    @ImranAhmed-wd5tr Před 4 lety

    awesome solution !! btw what software do you use to draw on the screen? can you please share the name

  • @aadityakiran_s
    @aadityakiran_s Před 9 měsíci

    The same method I came up with in C#. In large test cases TLE comes.

  • @ethanhunt3671
    @ethanhunt3671 Před 2 lety

    How we can solve this using Dijkstra with the constraint of 'K' stops. It's a greedy method, will it work here ? If there is no constraint for 'K' stops, then it would work for sure!

  • @ritikgoyal6087
    @ritikgoyal6087 Před 2 lety

    A small optimization which we can make in the given code acc to me. I think on line 16 we can replace

  • @manthankhorwal1477
    @manthankhorwal1477 Před 3 lety

    why we are taking visited array ?
    suppose if src=0 ,dst =3
    1 path -> 0->1->2->3 and suppose 1->2 cost is 500 and u made 2 visited
    2 path -> 0->2->3 and suppose 0->2 cost is 100 but u made 2 visited so we cant go there but it will be minimum cost path
    Please explain?

  • @shivendrasonkar6363
    @shivendrasonkar6363 Před 4 lety +1

    Please make video on graph with some questions

  • @unanimousdisclosed7482
    @unanimousdisclosed7482 Před 2 lety +2

    This approach is giving TLE

  • @shashankagrawal2378
    @shashankagrawal2378 Před 4 lety

    Hi,
    The same question can be solved using Bellman Ford or dijkstra algorithm, If possible please update on the same, or create a new video, As I was checking some other solution and these two seems to be efficient than dfs.
    Not sure though but Bellman Ford uses concept of dp also.

  • @rohitsai806
    @rohitsai806 Před 4 lety

    Grt explanation. I solved it using the same way. I know dijikstras but how can we do it when there is parameter k using dijikstras algorithm

  • @umatrilok9065
    @umatrilok9065 Před rokem

    Can anyone post java code with same prototype/algorithm

  • @ajitkumaryadav8298
    @ajitkumaryadav8298 Před 3 lety +1

    Content is very useful, I appreciated! WARNING RUBBISH ADS: { Actually I got some ads like: " In order to take my girlfriend on dinner so I started " , bhai etna bhauk kyo ho rha toda sabar kar le dimag mat kharab kar.}

  • @charugupta7103
    @charugupta7103 Před 3 lety

    great

  • @kumarashutosh6402
    @kumarashutosh6402 Před 3 lety +1

    You explained very clearly,by the way i follow you channel,you really explain things very clearly,even the tough questions.But your solution is getiing tle on leetcode for this problem.

    • @techdose4u
      @techdose4u  Před 3 lety

      Use priority queue in implementation

  • @siddharthsaxena6495
    @siddharthsaxena6495 Před 2 lety

    can u please explain this question using dijkstra's algo.

  • @abdullahzaidan7394
    @abdullahzaidan7394 Před 4 lety +2

    sir how to do this question using dijkstra since there is a constraint of k?

    • @techdose4u
      @techdose4u  Před 4 lety

      Dint try it yet. But you cannot solve it using MST algos.

  • @prarthitmehra9108
    @prarthitmehra9108 Před 4 lety +1

    Nice video but you said that the time complexity of your algorithm is O(V+E) but I think it is O(V^V). Could you please explain or correct me if I am wrong?

  • @siddhartha.saif25
    @siddhartha.saif25 Před 3 lety +1

    very nice!

  • @randomrandom316
    @randomrandom316 Před 4 lety +1

    I think the test cases for this problem were not very exhaustive. You can see accepted answer in python and I think it does not even implement several optimizations and checks for test cases but it still passed.
    class Solution:
    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
    answer = 10**9
    from_city = {}
    for source, destination, price in flights:
    if source in from_city:
    from_city[source][destination] = price
    else:
    from_city[source] = {destination: price}
    stack = [(src,0, K)]
    while stack:
    start, cost, steps = stack.pop()
    if start!=dst:
    steps-=1
    else:
    answer = min(answer,cost)
    pass
    if steps>-2 and answer>cost and start in from_city:
    for destination in from_city[start]:
    price = from_city[start][destination]
    stack = [(destination, cost+price, steps)]+stack
    return answer if answer!=10**9 else -1

    • @techdose4u
      @techdose4u  Před 4 lety +1

      Yes I think that too. But just enjoy the accepted code for now :P

  • @nani4027
    @nani4027 Před 2 lety

    Can I use this solution in interviews??

  • @anuragpandey6760
    @anuragpandey6760 Před 4 lety +1

    great explananation

  • @MohanRaj-vp1zt
    @MohanRaj-vp1zt Před 3 lety +2

    Nice explanation , but this solutions give TLE on leetcode. Only bellman ford shall pass on leetcode

  • @manojboganadham9071
    @manojboganadham9071 Před 3 lety +2

    This method is giving TLE in leetcode

  • @shaswatdas6553
    @shaswatdas6553 Před 3 lety +6

    Awesome explanation. Bdw rap starts at 18:19. Thank me later :D

  • @amanjasathy5598
    @amanjasathy5598 Před 4 lety +1

    please make a video on operations on vector of vector (especially for comparators for vector of vector)

  • @vibekdutta6539
    @vibekdutta6539 Před 4 lety +1

    Sir, can't we apply union find kruskal algo for min weight path

    • @techdose4u
      @techdose4u  Před 4 lety +1

      That can also work because finding minimum cost spanning tree will also lead to min cost path. But they should be in the same component. I guess that's why you want to use union find.

    • @vibekdutta6539
      @vibekdutta6539 Před 4 lety +1

      Yes, but I thought of it and I think kruskal won't work coz the spanning tree could be from the left subtree of source to the right or any other subtree of the source, that ain't the path from source to destination we want

    • @techdose4u
      @techdose4u  Před 4 lety +1

      I thought about it and concluded that MST algos won't work because of K stop condition 😅

    • @vibekdutta6539
      @vibekdutta6539 Před 4 lety

      Yeah, me too, actually I didn't even see the problem and I committed about MST but then I knew the problem

  • @akakop
    @akakop Před 4 lety +1

    thanks

  • @96FireFist
    @96FireFist Před 4 lety +1

    Why is dfs with pruning less efficient than BFS?

    • @techdose4u
      @techdose4u  Před 4 lety

      Not less efficient. If you use BFS in combination with other DS then BFS will be more efficient.

  • @MahirHasancse21
    @MahirHasancse21 Před 4 lety +4

    Do You use backtracking in your DFS? That is really a Smart thinking.

  • @siddharthkumar2761
    @siddharthkumar2761 Před 4 lety +1

    Ahh, awesome trick. I was trying to implement dfs with memoization for a long time and felt going in wrong direction unless saw your trick. Can u help me with memoization approach as well? Thanks in advance.

    • @techdose4u
      @techdose4u  Před 4 lety

      Paste your code in comment or share the gist link. You can get help.

    • @siddharthkumar2761
      @siddharthkumar2761 Před 4 lety

      @@techdose4u
      Here is the code.. Its getting TLE
      class Solution {
      int INF = 0x3F3F3F3F;
      Map memo = new HashMap();
      public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
      Map[] graph = new HashMap[n];
      for(int i = 0; i < n; i++)
      graph[i] = new HashMap();
      for(int[] f : flights) {
      graph[f[0]].put(f[1], f[2]);
      }
      int ans = findMinimumCostPath(graph, src, dst, -1, K);
      return ans == INF ? -1 : ans;
      }
      int findMinimumCostPath(Map[] graph,
      int src, int dst, int stop, int maxStop){
      if(src == dst)
      return 0;
      int minCost = INF;
      String key = src + "-" + dst;
      for(Map.Entry entry : graph[src].entrySet()){
      if(stop < maxStop)
      minCost = Math.min(minCost, entry.getValue() +
      findMinimumCostPath(graph, entry.getKey(), dst, stop + 1, maxStop));
      }
      memo.put(key, minCost);
      return memo.get(key);
      }
      }

    • @VarunMittal-viralmutant
      @VarunMittal-viralmutant Před 2 lety

      @@siddharthkumar2761 Were u able to get memoization working ?
      With DFS+pruning but without memoization it runs into TLE

  • @crackthecode1372
    @crackthecode1372 Před 4 lety +1

    Nicely explained thanks, can u please tell me , why did u write this : visited [src]=false at the end??

    • @techdose4u
      @techdose4u  Před 4 lety +1

      This is just the same concept for cycle finding algo in graph. First mark a node visited and then explore. While returning back from the node, mark it as unvisited so that it can be explored in some other path as well.

    • @chirag8627
      @chirag8627 Před 3 lety

      He sets visited[src] = true so that while exploring some node, you don't visit it again. That can happen if there exist cycle in the graph. But setting it again to false after for loop so that that node can be visited in some other path as he explained.
      Actually here you can even avoid usage of visited array. Not using visited array in dfs will give you all different paths from source node to any other node. ALL DISTINCT PATH!! As you are pruning here by two constraints that are 1- k(at most k stops) and 2- smaller cost. You will get all the paths that are in bound of these two constraints. And we want one of them that is having smallest cost.
      Hope it helps. @TECH DOSE please correct me if I am wrong anywhere.
      Keep it up!! TECH DOSE, you are helping a lot of people!

  • @saurabhgupta4082
    @saurabhgupta4082 Před 3 lety +1

    please tell me algorithms which are important to master graphs

    • @techdose4u
      @techdose4u  Před 3 lety +1

      Please follow my graph playlist. I am making the important algos only.

    • @saurabhgupta4082
      @saurabhgupta4082 Před 3 lety

      @@techdose4u yes i am following this playlist & thank you for these awesome videos.i love the way you explain.

  • @mayankjain876
    @mayankjain876 Před 4 lety +1

    Can we find shortest path in a weighted graph with this approach?

    • @techdose4u
      @techdose4u  Před 4 lety

      The graph you saw is weighted. Recursion is always slower as compared to loops even for same number of observable operations. So go with Dijkstra. But DFS will always work but it won't be efficient.

    • @lovleshbhatt7797
      @lovleshbhatt7797 Před 4 lety

      yes we can but its too costly , Use djikstras or bellman ford to reduce the tc

  • @vamsia5543
    @vamsia5543 Před 4 lety +2

    @TECHDOSE Great Video Sir, can u please explain why are we making vis[src]=false; again after the recursive calls.
    Thanks in advance :).

    • @techdose4u
      @techdose4u  Před 4 lety +2

      We dont want to fall in a loop. So whenever we are processing a node, we don't want to travel to that node again while finding mincost from src to day and so we keep making each node true. Now as we return in our recursion, we will have to make it false so that the node can get included in some other path. This is just like cycle finding algorithm, where we make a node true and enter and while returning we make it false.

    • @vamsia5543
      @vamsia5543 Před 4 lety

      @@techdose4u got it thanks

  • @ayushagrawal6473
    @ayushagrawal6473 Před 3 lety +1

    I got TLE when I recently tried.

  • @JohnTosun
    @JohnTosun Před 3 lety

    Cost(1,2) = 200? In the question, it is not 100?

  • @adarsh5519
    @adarsh5519 Před 2 lety +1

    Sir this solution is giving tle .please check it

  • @hardikmishra7426
    @hardikmishra7426 Před 4 lety +3

    Bro please explain all the 6 approach you've listed

    • @techdose4u
      @techdose4u  Před 4 lety +1

      I will explain all in future but explaining them without a reference video is not possible now.

    • @hardikmishra7426
      @hardikmishra7426 Před 4 lety +1

      @@techdose4u sure bro... Thanks

  • @downtowngedi
    @downtowngedi Před 3 lety +1

    47 / 49 test cases passed. if I use DFS + Pruning.

  • @gaishiya7696
    @gaishiya7696 Před 2 lety

    Why this seems so similar to travelling salesman problem without this pruning? Or is it only me ?

  • @ismail8973
    @ismail8973 Před 3 lety +5

    47/49 test cases passed in leetcode using DFS approach. But I know the intension of the vedio was to learn DFS + pruning.

    • @techdose4u
      @techdose4u  Před 3 lety +5

      New TCs added. Please optimize the code

    • @027_surajkumar2
      @027_surajkumar2 Před 2 lety

      @@techdose4u i dont think any optimisation left in this approach,if u know pls tell us how to make it work for last few test cases on leetcode. it's failing in last 4 TCs .

  • @tarachandkumawat478
    @tarachandkumawat478 Před rokem +1

    Time Limit Exceeded in case of n = 100,

  • @nani4027
    @nani4027 Před 2 lety +1

    I'm getting TLE in leetcode for this approach! :(

  • @hs2075
    @hs2075 Před 4 lety +1

    Thanks for solution
    Pls also add solution using djikstra as i feel djikstra wont work here.

    • @techdose4u
      @techdose4u  Před 4 lety

      I haven't tried Dijkstra. May be we need to modify something there.

  • @antimony0004
    @antimony0004 Před 2 lety

    class Solution {
    public:
    void solve(int n,vectoradj[],int k,int src,int dst, vector&vis,int &ans,int cost){
    if(k

  • @spetsnaz_2
    @spetsnaz_2 Před 3 lety

    Code Link : techdose.co.in/cheapest-flights-within-k-stops-dfs-pruning-leetcode-787/

  • @biswadeepchakraborty5354
    @biswadeepchakraborty5354 Před 4 lety +1

    Hello sir based on the problem's explanation I have got a hunch about solving this problem using knapsack. Correct me if I am wrong

  • @dipanshukumrawal4880
    @dipanshukumrawal4880 Před 3 lety +2

    Sir this code is giving TLE

    • @techdose4u
      @techdose4u  Před 3 lety

      Please optimize the code with priority queue. I have written the bruteforce approach

  • @mehulvarshney3389
    @mehulvarshney3389 Před 3 lety +1

    This solution is getting TLE

    • @techdose4u
      @techdose4u  Před 3 lety

      Test cases are updated. Do some optimization on my code :)

  • @kumarsandiproy1548
    @kumarsandiproy1548 Před 2 lety +1

    it is giving TLE in leetcode .

  • @mukulbahedia645
    @mukulbahedia645 Před 2 lety +1

    question link dala karo bhai.

    • @techdose4u
      @techdose4u  Před 2 lety

      You can search using leetcode number. Name is also mentioned :)

  • @ankitkumarpathak6768
    @ankitkumarpathak6768 Před rokem

    its giving me TLE on 49th testcase out of 51

  • @sahilchoudhary1473
    @sahilchoudhary1473 Před 4 lety +3

    done it with same approach giving TLE on test 37.
    Here is my code :
    class Solution {

    void solve(vector adj, int src ,int dst, int k,int &fare,int totalCost,vector vis){
    if (k

    • @hrithikshrivastava1405
      @hrithikshrivastava1405 Před 4 lety +1

      In the code pass the adjacency list and the visited array by refernce , that is being copied a lot of times and thus giving tle

  • @ardalaaruna6315
    @ardalaaruna6315 Před 3 lety

    sir, pls write the code in JAVA also..

  • @aakashgoswami2356
    @aakashgoswami2356 Před 2 lety +1

    This solution is giving tle :(

    • @techdose4u
      @techdose4u  Před 2 lety

      Please optimize using heap for dijkstra

  • @kc8478
    @kc8478 Před 2 lety

    The solution not passing leet code tests and giving TLE. Please own what you publish on you tube.

  • @ecea044gauravgogoi2
    @ecea044gauravgogoi2 Před 2 lety

    Dijkstra won't work! u won't be able to store in the way the question asks!

  • @ashishshrivastava7489

    Although you have explained the pruning method still you have not used that in the code. Your solution is good but not optimized.

  • @rahulmishra4911
    @rahulmishra4911 Před 3 lety

    Not passing on Leetcode