Cheapest Flights Within K Stops | GOOGLE | BFS | Explanation ➕ Live Coding

Поділитися
Вставка
  • Опубліковано 21 гру 2024

КОМЕНТАРІ • 99

  • @pankajsuryavanshi8332
    @pankajsuryavanshi8332 Рік тому +31

    You are king of graph

  • @souravjoshi2293
    @souravjoshi2293 Рік тому +12

    No one can teach graph so gracefully like you do. You are different
    People will soon know about you

  • @JJ-tp2dd
    @JJ-tp2dd Рік тому +9

    Happy Republic Day bhai. Thanks, below is the Java implementation:
    class Solution {
    public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
    int[] distance = new int[n];
    Arrays.fill(distance, Integer.MAX_VALUE);
    Map adj = new HashMap();
    for(int [] flight : flights){
    adj.computeIfAbsent(flight[0], value -> new ArrayList()).add(new Pair(flight[1], flight[2]));
    }

    // bfs
    Queue q = new ArrayDeque();
    q.add(new Pair(src, 0));
    distance[src] = 0;
    int steps = 0;

    while(!q.isEmpty() && steps 0){
    int u = q.peek().node;
    int price = q.peek().price;
    q.poll();
    if (!adj.containsKey(u))
    continue;
    for(Pair p : adj.get(u)){
    int v = p.node;
    int cost = p.price;

    if(distance[v] > price + cost){
    distance[v] = price + cost;
    q.add(new Pair(v, price+cost));
    }
    }
    }
    steps++;
    }

    return distance[dst] == Integer.MAX_VALUE ? -1 : distance[dst];
    }
    }
    class Pair {
    int node;
    int price;

    Pair(int _node, int _price){
    this.node = _node;
    this.price = _price;
    }
    }

  • @yogeshkumarverma2125
    @yogeshkumarverma2125 Рік тому +3

    Your voice is very friendly, keep up the good work

  • @kareni7572
    @kareni7572 6 місяців тому +1

    Glad to finally understand it cleanly! Much Appreciated!

  • @mayankupreti6966
    @mayankupreti6966 7 місяців тому +1

    One of the best solution out there for this question..

  • @nagmakhan3165
    @nagmakhan3165 Рік тому +3

    The explanation made things easy 🔥🔥🔥

  • @SuyashTalks
    @SuyashTalks Рік тому +2

    Top Notch Content 🚀

  • @dhruvsagar6577
    @dhruvsagar6577 Рік тому +1

    kaash mera college bhi aise padhata btw you are awsm

  • @sachinpatil929
    @sachinpatil929 Рік тому +2

    Nice that I found your channel , Please never stop to make videos , Eventually you will be famous for sure.
    bro i done all concept of still not able to solve question but way of your teaching i am sure one day i will be master in DSA.thanks alot for this type of content.

    • @codestorywithMIK
      @codestorywithMIK  Рік тому +1

      Thanks Sachin ❤️
      Welcome to my channel 😊

    • @sachinpatil929
      @sachinpatil929 Рік тому +1

      @@codestorywithMIK waiting many more dsa concepts video specially on recursion that make too fear of cp

  • @EB-ot8uu
    @EB-ot8uu 10 місяців тому

    people are right. indeed you are the king of graphs

  • @dojoPojo
    @dojoPojo Рік тому +1

    Legend on the way 👨‍💻 YOU ARE AMAZING

  • @Akashkumar_12
    @Akashkumar_12 10 місяців тому

    You are a best master of dsa

  • @ankitshaw_3060
    @ankitshaw_3060 Рік тому +3

    We can also omit the isempty check from the while loop as in constraints it is given that k is always less than n .....in simple word we are doing relaxation of nodes for k times and also thank you for providing such content your way of explaining concepts is really nice...❤❤

  • @darkstudio3170
    @darkstudio3170 Рік тому +4

    A imp consderation , we can't use PriorityQueue here (my first instinct was to use pQ) , because it might happen that the shortest path to the des can have more number stops and it blokes the other larger path which have less number of stops.

    • @kareni7572
      @kareni7572 5 місяців тому +1

      Was looking for this comment!

    • @priyajaiwal8072
      @priyajaiwal8072 25 днів тому

      @@kareni7572 i dont understand why pq is not used? we are almost doing Djikstra here

  • @--Blood--Prince--
    @--Blood--Prince-- Рік тому

    Bohot bdhiya explanation sir❤

  • @adityasehdev514
    @adityasehdev514 Рік тому +9

    bhaiya why cant we do this using Dijkstras because in your Graph concept and questions playlist you mentioned in questions where "source" and "destination" is mentioned we usually use Dijkstras. Moreover don't we use BFS in shortest path questions when graph is unweighted or is there no as such restriction. One last request can you please clarify when to use dijkstras and when to use BFS in such questions.
    last me bhaiya thank you so much for your efforts your teaching style is really unique.

    • @nirmalgurjar8181
      @nirmalgurjar8181 6 місяців тому +2

      This video is using modified Dijkstra algorithm but using queue. if we use priority queue then we will only process min prices nodes and can miss nodes going to correct answer, so eliminate this scenario dijkstra is implemented using queue.

    • @ayaanrashid960
      @ayaanrashid960 5 місяців тому +1

      @@nirmalgurjar8181 bcuz here stops are more prioritizing than distance, Dijkstra will surely find shortest path but it may use more stops than required

    • @nirmalgurjar8181
      @nirmalgurjar8181 5 місяців тому +1

      @@ayaanrashid960 not just stop, its stop + cheapest. queue will take care of stop and diksktra will take care of cheapest price. That's why its modified Dikstra algorithm.

  • @sauravkumarsonu5539
    @sauravkumarsonu5539 Рік тому +1

    Great Explanation bhai 🔥🔥❤❤❤❤

  • @shivkumar-og4ow
    @shivkumar-og4ow Рік тому +1

    nice explanation bhaiya..

  • @saumyaranjan9256
    @saumyaranjan9256 Рік тому +1

    Best explanation for this question.

  • @deepikasoni6916
    @deepikasoni6916 10 місяців тому

    Just Awsm Explaination, Thank You🌟

  • @sudhanshushekhar4222
    @sudhanshushekhar4222 Рік тому +1

    amazing explanation 👌👌

  • @satyamkumaryadav1560
    @satyamkumaryadav1560 Рік тому +1

    everyone thinking of dijkstra and using priority queue
    but i think hhere we are not using priority queue
    because its not about the shortest or cheapest path but with cheapest and k stops
    so if we use priority queue and condition of k stops then it may be possible we can not reach destination

    • @satyamkumaryadav1560
      @satyamkumaryadav1560 10 місяців тому +1

      again got stuck with this thought thank god i commented this thing on youtube

  • @AnkitSingh-tm5dp
    @AnkitSingh-tm5dp Рік тому +1

    He is like iron man in marvel 🔥

  • @anshugupta3269
    @anshugupta3269 Рік тому +2

    thank you sir

  • @prudhvirajmacherla9854
    @prudhvirajmacherla9854 10 місяців тому

    Simply understood

  • @priyajaiwal8072
    @priyajaiwal8072 25 днів тому

    Great explanation, MIK. One thing is, I don't understand why pq is not used. We are almost doing Djikstra here?

  • @gauravbanerjee2898
    @gauravbanerjee2898 10 місяців тому

    Thanks a lot bhaiya ❤❤

  • @gauravbanerjee2898
    @gauravbanerjee2898 10 місяців тому

    Congrats for 19k subs 🎉🥳

  • @manishv.8167
    @manishv.8167 Рік тому

    Waiting for the next concept video, This is great video 😁

    • @codestorywithMIK
      @codestorywithMIK  Рік тому +1

      Yep soon.
      I hope we all are now able to solve Graph Qns.
      Hope we all grow more

  • @AnandKumar-kz3ls
    @AnandKumar-kz3ls Рік тому +1

    You just invented Dijkstra's algorithm

  • @piyushacharya7696
    @piyushacharya7696 Рік тому +1

    Let's go😎😎

  • @Mohit-fe5hx
    @Mohit-fe5hx 10 місяців тому +1

    suggestion: please variable naming ko clear rkho,ese confusion create kr rhi h..

    • @codestorywithMIK
      @codestorywithMIK  10 місяців тому

      Sure thing.
      Suggestion taken. Thank you ❤️🙏

  • @parthbhatti4151
    @parthbhatti4151 10 місяців тому

    Intution is very simple but when we go for code it becomes tough specially in java right?

  • @honey6567
    @honey6567 Рік тому +1

    great

  • @ruchirshrikhande5584
    @ruchirshrikhande5584 10 місяців тому

    Hi, can we solve this using Dijikstra algorithm?Why or why not?Seems like a similar problem to Network delay time

    • @akmarkan2490
      @akmarkan2490 Місяць тому

      Just write Simple dijkstra code but with normal queue.

  • @satyamjha37
    @satyamjha37 Рік тому +1

    outstanding explanation man!!
    but ye intuition building kaise achi hogi?
    sometimes i just go on another track.
    kuch jyada hi soch leta hu😅😅

    • @codestorywithMIK
      @codestorywithMIK  Рік тому +2

      Thanks Satyam.
      Actually I have noticed , intuition generally comes from the most basic thing that we are aware of.
      For example: Here in this Qn, I thought about the most basic thing we can think of about Graph that is the BFS.
      And then i run around BFS until I figure out what are the cases required for solving a particular qn.
      I would always suggest strengthening in the basic and obvious concepts which we tend to miss because of thinking too much.
      I am pretty sure this will improve with time and with solving more and more Qns

    • @satyamjha37
      @satyamjha37 Рік тому +1

      @@codestorywithMIK Oh!! Definitely gonna use this tip now on. Thanks for clearing this👍

    • @AnkitSingh-tm5dp
      @AnkitSingh-tm5dp Рік тому +1

      @@satyamjha37 helpful

  • @dibbodas4116
    @dibbodas4116 Місяць тому

    bhaiya please explain the time and space complexity separately

  • @shabananoor9423
    @shabananoor9423 Рік тому

    Masterpiece

  • @samarthsinghthakur
    @samarthsinghthakur 10 місяців тому

    here we are not maintaining seen set to mark visited, what if there is cycle b/w node

    • @amitguptapc
      @amitguptapc 10 місяців тому

      will go for max k stops, so it wont end up in an infinite cycle

  • @drbullah1388
    @drbullah1388 Рік тому +1

    Bhaiya ye djikstras se bhi to kar sakte the na BFS ke badle?

    • @codestorywithMIK
      @codestorywithMIK  Рік тому

      Yes. And with many other approaches.
      I will soon share other approaches too

    • @gurnoorchhabranit-jalandha5002
      @gurnoorchhabranit-jalandha5002 Рік тому

      @@codestorywithMIK brother i am currently in 2nd year
      Currently i have one full year for coding
      Bhai plss ek baari aap trees and graphs ka ek tagda playlist banado 😭😭 mere bhut help ho jaege

    • @codestorywithMIK
      @codestorywithMIK  Рік тому +1

      Sure Gurnoor,
      Graphs Concept playlist is in progress (you can see it), i have explained there from scratch.
      And i will create other playlists soon.
      Currently travelling and will be on break for 3 weeks.
      Will be back with more awesome contents

    • @girikgarg8
      @girikgarg8 Рік тому

      @@codestorywithMIK Yup and please compare their time complexities too

    • @gurnoorchhabranit-jalandha5002
      @gurnoorchhabranit-jalandha5002 Рік тому +1

      @@codestorywithMIK 😌😌 ok bhaiya aapka samjhane ka method bilkul hatke hai aap ache see trees graphs karado mera kaam bn jayega

  • @akmarkan2490
    @akmarkan2490 Місяць тому

    Wasn't it just Dijkstra with Normal Queue???

  • @nirmalgurjar8181
    @nirmalgurjar8181 6 місяців тому

    This is modified BFS with Dijkstra Algorithm.

  • @alisheheryar1770
    @alisheheryar1770 7 місяців тому

    Ey sharma verma dharma. Aj ki daaru mery pay!

  • @codeandtalk6
    @codeandtalk6 10 місяців тому

    ❤❤❤

  • @aws_handles
    @aws_handles 10 місяців тому

    ❤❤

  • @hemendrachaudhary3263
    @hemendrachaudhary3263 10 місяців тому

    if there is a cycle then how we gonna handle that ?

    • @kushaagrgupta105
      @kushaagrgupta105 6 місяців тому

      We are only adding to queue if distance is lesser. It can only happen finite number of times

  • @abhayrai1724
    @abhayrai1724 Рік тому +1

    ❤‍🔥

  • @nk-fs8bj
    @nk-fs8bj 10 місяців тому

  • @dhirunand
    @dhirunand Рік тому

    Some extra test case added and this code is giving wrong answer

    • @codestorywithMIK
      @codestorywithMIK  10 місяців тому

      It seems to passing for me
      Tried Submission today also - leetcode.com/submissions/detail/1183541862/
      Can you kindly check again.

  • @recessionriche
    @recessionriche Рік тому

    Video on bellman's approach?
    class Solution {
    public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
    int[] dist = new int[n];
    Arrays.fill(dist, Integer.MAX_VALUE);
    dist[src] = 0;
    for (int i = 0; i

    • @codestorywithMIK
      @codestorywithMIK  Рік тому

      Soon in my Graph Concepts playlist after i teach that topic 😊

  • @varuntanwar6746
    @varuntanwar6746 11 місяців тому

    It gives TLE

    • @codestorywithMIK
      @codestorywithMIK  10 місяців тому

      It seems to passing for me
      Tried Submission today also - leetcode.com/submissions/detail/1183541862/
      Can you kindly check again.

  • @bhuppidhamii
    @bhuppidhamii 10 місяців тому +1

    Need to learn graph, I was ignoring graph

    • @codestorywithMIK
      @codestorywithMIK  10 місяців тому +1

      Try my Graph Concepts Playlist.
      I am sure you will love Graph after that ❤️🙏
      ua-cam.com/play/PLpIkg8OmuX-LZB9jYzbbZchk277H5CbdY.html&si=0vH62FqyFSXJOjxd

  • @avneetsingh4896
    @avneetsingh4896 Рік тому

    WHILE (N--) KARKE KYU BFS KIYA CAN U EXPLAIN

    • @codestorywithMIK
      @codestorywithMIK  Рік тому

      To cover all nodes in current level at once.
      This is the way we do BFS whenever we want to process all nodes level by level

  • @adhikari669
    @adhikari669 Рік тому

    bhaya mera tle arra h

    • @codestorywithMIK
      @codestorywithMIK  Рік тому

      Can you share your code

    • @sudhanshushekhar4222
      @sudhanshushekhar4222 Рік тому

      most possible problem according to me is ........ shayad tumne q.pop() ; nahi kiya hoga please check

  • @Mohit-fe5hx
    @Mohit-fe5hx 10 місяців тому +1

    while(N--- )kyu kr rhe ,ek baar explain kr skte ho please...wo smjhe nhi

    • @codestorywithMIK
      @codestorywithMIK  10 місяців тому

      It can also be written as
      while(N > 0) {
      //do stuff
      N- - ;
      }
      Both are same.

  • @ayanroy2050
    @ayanroy2050 Місяць тому +1

    class Solution {
    public:
    // int dijkstra(int n,int src,int dst,int k,vector&graph){
    // }
    int findCheapestPrice(int n, vector& flights, int src, int dst, int k) {
    vectorgraph(n);
    for (auto it:flights){
    graph[it[0]].push_back({it[1],it[2]});//node ,price
    }
    //return dijkstra(n,src,dst,k,graph);
    int mini=1e9;
    vectordistance(n,1e9);
    priority_queuepq;
    distance[src]=0;
    pq.push({{0,src},0});
    while(!pq.empty()){
    int node=pq.top().first.second;
    int dist=pq.top().first.first;
    int step=pq.top().second;
    pq.pop();
    if(node==dst){
    if(step

  • @theOmKumar
    @theOmKumar 10 місяців тому

    RECURSION + MEMO:::
    class Solution {
    int dp[102][102];
    public:
    int getCheapestPrice(int currentCity, int& destination, int remainingStops, vector& adjList) {
    if (currentCity == destination) { //it will cost 0 to reach destination
    return 0;
    }
    if (remainingStops < 0) {//invalid flight path
    return INT_MAX;
    }
    if (dp[currentCity][remainingStops] != -1) {
    return dp[currentCity][remainingStops];
    }
    int minPrice = INT_MAX;
    //explore all neighbor city and return min price
    for (auto& neighbor : adjList[currentCity]) {
    int neighborCity = neighbor.first;
    int price = neighbor.second;
    int nextPrice = getCheapestPrice(neighborCity, destination, remainingStops - 1, adjList);
    if (nextPrice == INT_MAX) { //if invalid path skip(can cause overflow)
    continue;
    }
    minPrice = min(minPrice, price + nextPrice);
    }
    return dp[currentCity][remainingStops] = minPrice;
    }
    int findCheapestPrice(int numCities, vector& flights, int source, int destination, int maxStops) {
    // source -> {destination, price},.....
    vector adjacencyList(numCities);
    for (auto& flight : flights) {
    int source = flight[0];
    int destination = flight[1];
    int price = flight[2];
    adjacencyList[source].push_back({destination, price});
    }
    memset(dp, -1, sizeof(dp));
    int cheapestPrice = getCheapestPrice(source, destination, maxStops, adjacencyList);
    return cheapestPrice == INT_MAX ? -1 : cheapestPrice;
    }
    };

  • @dayashankarlakhotia4943
    @dayashankarlakhotia4943 10 місяців тому

    your java code change this line Listneighbors=adj.getOrDefault(u,Collection.emptyList) change this.
    if(!adj.containsKey(u)) continue;
    for(int[]neighbor:adj.get(u)){