G-10. Rotten Oranges | C++ | Java

Sdílet
Vložit
  • čas přidán 8. 09. 2024
  • GfG-Problem Link: bit.ly/3oekoir
    C++/Java/Codes and Notes Link: takeuforward.o...
    DP Series: • Striver's Dynamic Prog...
    SDE Sheet: takeuforward.o...
    Check out our Website for curated resources:
    Our Second Channel: / @striver_79
    In case you are thinking to buy courses, please check below:
    Code "takeuforward" for 15% off at GFG: practice.geeks...
    Code "takeuforward" for 20% off on sys-design: get.interviewr...?_aff=takeuforward
    Crypto, I use the Wazirx app: wazirx.com/inv...
    Take 750 rs free Amazon Stock from me: indmoney.oneli...
    Earn 100 rs by making a Grow Account for investing: app.groww.in/v...
    Linkedin/Instagram/Telegram: linktr.ee/take...
    ---------------------------------------------------------------------------------------------------------------------------

Komentáře • 381

  • @takeUforward
    @takeUforward  Před 2 lety +153

    Let's continue the habit of commenting “understood” if you got the entire video. Please give it a like too, you don't 😞
    Do follow me on Instagram: striver_79

    • @animecontent2056
      @animecontent2056 Před 2 lety +8

      Don't have an account in Instagram
      and it distracts me much more than anyone does 😎😎😎

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

      Understood

    • @herculean6748
      @herculean6748 Před 2 lety

      I am yet to start Tree and Graph, should start graph first? or do I need to do tree first?

    • @getgoin2217
      @getgoin2217 Před rokem +1

      really appreciate you putting quality content , but did not understand from explanation so clarifying here my understanding the TC is O(n*m) because of adding starting points in the queue + O(n*m*4) is because of BSF also worst case is not all oranges being fresh but 1 orange being rotten with rest all being fresh

    • @Codebond7
      @Codebond7 Před rokem

      where is java code I am unable to find

  • @sidduroy9150
    @sidduroy9150 Před 2 lety +439

    I can complete the whole playlist in one day , coz it's just like a Webseries 😂😊, Offcourse it's only bcoz of the Lead character: striver

  • @av21015
    @av21015 Před rokem +112

    I really appreciate your dedication. This video is already recorded in stacks and queues playlist but you have recorded it again here. And this video is better than previous one.

    • @takeUforward
      @takeUforward  Před rokem +60

      Yes, true, I agree

    • @patrickishere
      @patrickishere Před rokem +2

      ​@@takeUforward which tool do you use to explain? it is so good !

  • @rishabhsingh3873
    @rishabhsingh3873 Před rokem +35

    for delRow and delCol we can use array directions = {-1, 0, 1, 0, -1} and inside for loop for neighbor row and column we can use int nRow = r + directions[i];
    int nCol = c + directions[i+1];

    • @shiblijamal8544
      @shiblijamal8544 Před 8 měsíci +3

      Anything is fine make sure the coordinates traverse all those direction that's it... Btw good thinking

    • @LowkeyCoder
      @LowkeyCoder Před 8 měsíci +1

      cool stuff!

  • @DPCODE72
    @DPCODE72 Před 2 lety +27

    In 20:35, Striver was trying to say about The industry's requirements over the data. While teaching he wants to teach about everything that is required for a Company.

    • @takeUforward
      @takeUforward  Před 2 lety +20

      Yes, in interviews they do care about these small things.

    • @DPCODE72
      @DPCODE72 Před 2 lety +10

      @@takeUforward While(1){
      cout

    • @Sp_Global-oc4tf
      @Sp_Global-oc4tf Před 2 měsíci +5

      @@DPCODE72 ; kon dega?

  • @NaveenKumar-os8dv
    @NaveenKumar-os8dv Před 2 lety +51

    it seems easy when we see the video, but it is difficult when it comes to actually code, but I think I am getting better. It's really just the game of converting your "thinking into coding". If we can do this, we can solve any problem.

    • @thatindianboy2817
      @thatindianboy2817 Před 2 lety

      How do you ensure the resultant answer is minimum?

    • @Harshanandita
      @Harshanandita Před rokem +2

      Based on the question, in 1 sec any rotten orange could rotten only its top-bottom or left-right neighbours
      So, it's simple step by step calculation, done using BFS

    • @ashwanisharma8903
      @ashwanisharma8903 Před rokem +1

      @@thatindianboy2817 Bcz BFS is level order traversal. At each level we are keeping time as same. Same bcz when we dequeue one coordinate for all its four directions we will do +1 to value that was dequeued. So each level will have same time.

  • @divyanshd5557
    @divyanshd5557 Před 2 měsíci +3

    it could have been done by the vector as well..just instead of vector vis it should be vector vis(n,vector(m,0))

  • @KratosProton
    @KratosProton Před 2 lety +24

    Striver sir, can you please also cover LC 909. Snakes and Ladders in your playlist too, nobody on yt has explained this problem yet. Just a humble request

  • @SatyaMantha
    @SatyaMantha Před rokem +12

    Striver, I like the way you make toughest problems look so easy with your explanation. Kudos to you!

  • @gabru6809
    @gabru6809 Před 2 lety +20

    When would the whole series be uploaded? 😅

  • @vaibhavagarwal2421
    @vaibhavagarwal2421 Před rokem +3

    instead of using pair we can use vis grid to store the time as well

  • @RohitKumar-dz8dh
    @RohitKumar-dz8dh Před rokem +2

    For sure no one need to worry about code in any language after getting approach how to tackle problem 😊. Thanks again .

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

    understood bahut chota compliment hai.... Dil khush hojata hai aap say padke bhai

  • @rohitkumarpilania94
    @rohitkumarpilania94 Před rokem +2

    can be done withput the visited array, just keep rotting the oranges in grid by marking them as 2

    • @ankita7119
      @ankita7119 Před 2 měsíci

      but it is advised not to alter the question

  • @johnj171
    @johnj171 Před 2 měsíci

    really great but what is exceptional is the connection you create between every problem and the volume of problems solved it builds up a strong foundation for every one slowly and strongly highly recommended for every one!!!!!!!!

  • @iflifewasmovie4766
    @iflifewasmovie4766 Před 2 lety +8

    I was waiting to not start too soon and still see I am here in 10th lecture and it feels like a piece of cake this time....ALL THANKS TO YOU!! Waiting for all the videos..(DESPERATELY) ❤❤

  • @FooBar-lb5wf
    @FooBar-lb5wf Před 2 měsíci

    Thanks, Striver. I can think of a couple of optimizations. First, we can avoid the last nested loop to check if all the fresh oranges are now rotten by just keeping two counters; freshcnt and rotcnt, with freshcnt representing the initial count of fresh oranges (can be counted in the initial nested loops) and rotcnt representing those fresh oranges which were rotten after coming in contact with rotten oranges (can be updated in the BFS logic when we update the visited array). If the two counts do not match, we can return -1. The second optimization is around the udpate of time t. We should be able to safely update t with the new value since BFS order would ensure that all the nodes with time 'ts' are processed before the nodes with time 'ts+1'. So the value of t should be monotonic in nature and so checking max(tm, t) may be redundant.

  • @amansinghal4663
    @amansinghal4663 Před rokem +9

    Just one correction bhaiya....
    I think there was no need of using the max function for finding the time. Without it also the code gets accepted. You can find my AC below:
    class Solution {
    public:
    int bfs(queue&q, vector&visited, vector& grid, int rows, int columns){
    int directions[5] = {0,-1,0,1,0};
    int time=0;
    while(!q.empty()){
    pairpr = q.front();
    q.pop();
    time = pr.second;
    for(int k=0; k=0 && nrow=0 && ncol

    • @elizabethr5161
      @elizabethr5161 Před rokem

      Yes bro, you are right, since we use queue to store the time, there is no need of max variable.

  • @shashank820
    @shashank820 Před 2 lety +5

    Understood 🤓
    10 lectures done. Waiting for next videos bhaiya 🙃

  • @abhinavsingh8090
    @abhinavsingh8090 Před měsícem

    we can use vector to store visited matrix instead of vectorvis it will be vectorvis(n, vector(m,0));

  • @codewariors
    @codewariors Před 28 dny

    very easy to understand . hats off strivers

  • @tasneemayham974
    @tasneemayham974 Před 7 měsíci

    THANK YOUUU STRIVERRR!!!!
    Python Code for those who need it:
    class Solution(object):
    def orangesRotting(self, grid):
    ROWS, COLS = len(grid), len(grid[0])
    vis = [[0] * COLS for i in range(ROWS)]
    q = deque()
    cntFresh = 0
    for i in range(ROWS):
    for j in range(COLS):
    if grid[i][j] == 2:
    q.append((i,j,0))
    vis[i][j] = 2
    if grid[i][j] == 1:
    cntFresh += 1
    maxTime,cnt = 0,0
    delRow = [-1,0,+1,0]
    delCol = [0,+1,0,-1]
    while q:
    r,c,t = q.popleft()
    maxTime = max(maxTime,t)

    for i in range(4):
    nRow = r + delRow[i]
    nCol = c + delCol[i]
    if nRow >= 0 and nRow < ROWS and nCol >= 0 and nCol < COLS and vis[nRow][nCol] == 0 and grid[nRow][nCol] == 1:
    vis[nRow][nCol] = 2
    q.append((nRow,nCol,t+1))
    cnt += 1
    if cnt != cntFresh:
    return -1
    return maxTime

  • @ParasLeela
    @ParasLeela Před rokem +24

    it should be vis[nrow][ncol] = 2 instead of vis[nrow][ncol] = 1 otherwise we are never marking the fresh orange as rotten in the visited array

    • @jonascharles1686
      @jonascharles1686 Před rokem +4

      Yep, he changed it later but didn't show that in video

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

    Thanku sir for interview centric problem solving on graph because most of the UTube channels have algorithm of graph with no problem solving based on the concepts .

  • @prashudeshmukh7902
    @prashudeshmukh7902 Před rokem +6

    instead of pair........... we can use queue .
    keeping that aside ..amazing playlist bhaiya 👍👍

  • @manjitha24
    @manjitha24 Před 28 dny

    your explanation is so beautiful, soo elegant .. just like a woooww woowww🤩

  • @niranjanbhondave88
    @niranjanbhondave88 Před 2 měsíci

    I solved this question with a little bit of optimisation: while initialising queue, i maintained a fresh_count for number of fresh oranges. If grid[i][j] was 0 then visited[i][j] = 1, else if fresh orange then count++ else push in queue. each time i had a fresh orange, i marked visited ++ as well as count--. So to check for fresh oranges i didnt need another loop i just checked the count.If zero then only returned time else -1

  • @AtharvaRao0104
    @AtharvaRao0104 Před 16 dny

    Though striver explains approach very well, there can be improvements to code.
    Beginners/college students may be happy with such code, as it solves the problem.
    But it soon becomes a habit to just focus on working code and readability is not given due importance.
    Interviewers with a few years of industry experience, may find such code annoying.
    So when you solve the problem also think what names can convey the logic clearly. Clarity in thinking will reflect in code too.
    One improvement is : some names have to be meaningful
    1. Instead of Pair class - the class could have had a meaningful name like RottenOrange class , with row, column and time at which it got rotten. (or even an Orange with more attributes)
    So we will be adding RottenOranges into the queue. That is what is central idea right processing the rotten oranges. (Pair here was absolutely inappropriate as we are storing 3 attributes)
    First add the initial rotten oranges into the Queue .
    Later do a BFS - while queue is not empty - pop a rotten orange and check if any of the neighbouring slots have a fresh orange which is not visited yet. If yes, then make it rotten and add it to the queue of rotten oranges.
    2. Also a method can be added like: computeNeighbouringSlot and checkValidityOfNeighbouringSlot(nrow, ncol) instead of having complex computations. We need to abstract them to methods with clear names to understand the main logic.
    Such improvements can greatly add readability to code (basic requirement of a software engineer) and will abstract the implementations so that the reader doesnt have to strain to understand the logic.

  • @googleit2490
    @googleit2490 Před 9 měsíci +3

    Graph Revision:
    Done and dusted in Graph Revisiion (BFS)
    (10 mins)
    Nov'24, 2023 11:27 pm

  • @adebisisheriff159
    @adebisisheriff159 Před 8 měsíci +1

    Thanks so oooooooooooooooooooooooooooooooooooooooo much Striver. We love you!!!

  • @shivayadav-po8un
    @shivayadav-po8un Před 4 měsíci

    the major difference is when you see other tutorials, you can't write code until you see their code multiple times. In case of striver, his explanation is more than enough and our code just flows without even seeing striver's code. Take a bow#Striver

  • @abhijeetkumar2970
    @abhijeetkumar2970 Před rokem +1

    understood

  • @harshkilaji1901
    @harshkilaji1901 Před rokem +3

    Can we not instead find the nearest '2' or rotten orange for each '1' (fresh oranges) ?? And the answer would be the distance between farthest 2 and 1. If that '1' is unreachable we will automatically get -1. I guess we can also apply Dynamic programming to find subsequent distances.

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

    pls jaldi jaldi laaiye graphs ke or lecture....you r the best explainer

  • @knox9450
    @knox9450 Před měsícem +1

    18:14 at this instead of 1 it should be 2 as we marking it rotten in vis array

  • @strickler453
    @strickler453 Před rokem +1

    "understood"
    initially i thought : we can do without using extra space(true).
    but at the end : i got to know that don't lose the original input as company don't want to alter original data.

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

    You are so good that I solved it in 1st attempt just thinking the right way which you taught us to do all these times. Thanks. I learned the whole graph from you.. for this question I watched only 1 minute of your video. haha!

  • @ManishKumar-zk5ky
    @ManishKumar-zk5ky Před rokem +2

    sir your explanation is very good Thank you🤩

  • @AryanGairola-th3qc
    @AryanGairola-th3qc Před 4 měsíci

    understood done a very lengthy code because of you
    thankyou man...

  • @afuadajoemmanuel5735
    @afuadajoemmanuel5735 Před 2 měsíci

    Thanks for all you do Striver 🙏

  • @soumikpaul6503
    @soumikpaul6503 Před 8 měsíci

    The best video to understand BFS

  • @shuvbhowmickbestin
    @shuvbhowmickbestin Před rokem

    One thing, instead of creating a visited 2d matrix we can also take a set which stores pairs of coordinates visited already, that makes it easier to maintain.

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

    Understood! So awesome explanation as always. I guess this might one of the way to fill an area of one color with a different color in 2D field.... Anyway, thank you very much for your explanation!!

  • @VaibhavSingh-vy6gy
    @VaibhavSingh-vy6gy Před rokem +1

    Rotten Oranges felt like a piece of cake😂.... thnx to striver

  • @rahulsidhu5945
    @rahulsidhu5945 Před rokem

    Striver you are awesom, and that's why you are my inspiration. Thank you for everything🙂🙂

  • @priyanshajmera3177
    @priyanshajmera3177 Před rokem

    Great explanation.
    But we don't need visited here so we can save some space.

  • @ujjawaltyagi8540
    @ujjawaltyagi8540 Před rokem

    understood !!
    Absolutely nailed the question (made it an easy cake walk )

  • @vaishnavimore4860
    @vaishnavimore4860 Před rokem +1

    Thank you for making such great playlist!! Completely understood🚀

  • @dhyanprasad5611
    @dhyanprasad5611 Před rokem +1

    OP OP oP OP OP, this series is FIRE !!

  • @original_gangsta_
    @original_gangsta_ Před rokem +1

    Understood
    ✌✌

  • @priyanshkumar17
    @priyanshkumar17 Před 3 měsíci

    understood !! Wonderfully explained... Thanks Striver Bhaiya :)

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

    10 videos completed.. waiting for the next

  • @AbhayKumar-gl5hh
    @AbhayKumar-gl5hh Před rokem +3

    I understood the concept but I have a question,
    we chose to take a max of the time(i.e tm=max(tm,t)) but I cant think of any test case in which if we apply to get correct answer if we don't take max of time inside the BFS, BFS automatically takes care of finding of the minimum possible time to rot all apples so why bother to take the max? I tried to run the code without the taking max of time and it worked. I might be missing something here if I'm please help.

    • @subhamoyburman3093
      @subhamoyburman3093 Před rokem +1

      I also think so, I even put it in gpt to give me TC which would violate this it did not provide anything valid.

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

    Understood. Also could i used queueq; data strucutre. Will it impact on Runtime Complexity or Space?

  • @Yash-uk8ib
    @Yash-uk8ib Před rokem +1

    I think we do not have to maintain time at each step. Simplu counting levels in multisource bfs will do the job!

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

    Understood
    I watch it on your codeBeyond using node and submitted correctly

  • @tusharkumarroy-tj2qg
    @tusharkumarroy-tj2qg Před 6 dny

    understood 70 percent

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

    Hi I am new to DSA, I would like to request you make a comprehensive video explaining what topics should I do and in what order in Arrays, Strings, Stacks, Queues..
    GFG is huge and i cant figure out what to do and leave.

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

    Understood! So awesome explanation as always

  • @Saurav_Kumar514
    @Saurav_Kumar514 Před rokem +2

    Amazing explanation man! 🔥👌

  • @pratikdas1780
    @pratikdas1780 Před rokem

    UNDERSTOOD SIR. you're an angel.

  • @NODEZEN-s8e
    @NODEZEN-s8e Před 19 dny

    Also I guess you don't need tm=max(tm,t) as in BFS when you have rotten one fresh orange its time has been increased by level 1 and if you are rotting by that orange than count will increase but ya you need to change grid[i][j] to 2 when you are putting in queue which might not be good for you as you are changing input .

  • @systempesystm
    @systempesystm Před měsícem

    Loved This !!!

  • @kritikarawat2180
    @kritikarawat2180 Před rokem

    Very easy explaination.Loved your explaination brother.

  • @aayushbisht4307
    @aayushbisht4307 Před rokem

    18:19 no need for maximum tm = t will work

  • @subhamoybera6456
    @subhamoybera6456 Před rokem +1

    Great explanation 👍

  • @subhranilsamanta2862
    @subhranilsamanta2862 Před 2 lety

    Understood the whole Series.👏🏽

  • @udatyadeb101
    @udatyadeb101 Před 11 měsíci +2

    did by myself

  • @Code_JAVA268
    @Code_JAVA268 Před 6 měsíci

    Kudos to you striver highly recommended 🎉❤

  • @user-kl3qv1sc8k
    @user-kl3qv1sc8k Před 3 měsíci

    Understood Striver!!

  • @mohmedfaizrozdarsyed1234
    @mohmedfaizrozdarsyed1234 Před 7 měsíci

    Thank you sir , Really appreciate your effort

  • @EngineerPlays2024
    @EngineerPlays2024 Před rokem +1

    Amazing vid man!

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

    Thank You So Much for this wonderful video.............🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @pardhi8959
    @pardhi8959 Před 6 měsíci

    hi striver i know you are busy, But pls make a video on how to make notes for your sde sheet and how to use the sheet effectivity.

  • @saumilaggarwal5233
    @saumilaggarwal5233 Před rokem +1

    thnx, but we can also do this question without visited 2D vector
    code:
    class Solution {
    public:
    int orangesRotting(vector& grid) {
    int m= grid.size();
    int n= grid[0].size();
    int tm=0;

    queue q;
    for(int i=0;i

    • @rahulkapoor7305
      @rahulkapoor7305 Před rokem

      Yes, as we are changing values to 2 from 1, so a check on this will take care of is visited or not as well.

  • @UECAshutoshKumar
    @UECAshutoshKumar Před rokem +1

    Thank you sir

  • @TheBaljitSingh
    @TheBaljitSingh Před 10 měsíci

    18:11 vis[nrow][ncol] should be equal to 2;

  • @KunalSingh-kn2ij
    @KunalSingh-kn2ij Před rokem +1

    STRIVER GOAT🤘🤘

  • @sripriyapotnuru5839
    @sripriyapotnuru5839 Před rokem

    Thank you, Striver

  • @chitranshjain5075
    @chitranshjain5075 Před 2 lety

    Completely UNDERSTOOD

  • @amanasrani6405
    @amanasrani6405 Před 4 měsíci

    At 18:13 it should be vis[nrow][ncol] = 2; instead of vis[nrow][ncol] = 2;

  • @LearnerForever123
    @LearnerForever123 Před rokem +1

    Understood

  • @codeman3828
    @codeman3828 Před 4 měsíci

    Understood.

  • @b_31mahammadzubair81
    @b_31mahammadzubair81 Před 2 lety

    Understood completely 🔥🔥 and waiting for the next video

  • @muchmunchies43
    @muchmunchies43 Před měsícem

    Understood!

  • @PrimeContent01
    @PrimeContent01 Před 11 měsíci

    understood this and all previous videos

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

    Two days before, this question was asked to me in Amazon SDE Intern Interview and i messed up!

  • @srinivasjayaram570
    @srinivasjayaram570 Před rokem

    The best explanation ever !

  • @rohitshrirame2378
    @rohitshrirame2378 Před 2 lety

    understood!!!! thanks for all of these!!!!!!

  • @user-tk2vg5jt3l
    @user-tk2vg5jt3l Před 4 měsíci

    thank you Bhaiya

  • @viratrunmachine815
    @viratrunmachine815 Před rokem

    you are truly legend sir

  • @aditya_raj7827
    @aditya_raj7827 Před 7 měsíci

    Understood 😊

  • @amarjeetkumar-hk2jl
    @amarjeetkumar-hk2jl Před 2 lety +1

    Understood but please upload more videos as fast possible

  • @ishangujarathi10
    @ishangujarathi10 Před rokem

    amazing intuition!!! understood!!

  • @1tav0
    @1tav0 Před 2 lety

    awesome. thnk u striver understood

  • @pranjalnama2420
    @pranjalnama2420 Před 3 měsíci

    Thanks amazing explanation

  • @rishabhgupta9846
    @rishabhgupta9846 Před rokem

    understood,great explanation

  • @anshumanbehera3706
    @anshumanbehera3706 Před rokem

    understood thanks for the amazing Explations

  • @shubhamyadav2623
    @shubhamyadav2623 Před rokem

    Just Amazing man !! I don't why all those idiots buys course if a guy like this giving us free !!
    We should support him for making such things free to us. Salute Striver🙋‍♀ good work bro!!

  • @Kshitijsingh-n7f
    @Kshitijsingh-n7f Před 18 dny

    second O(N*M*4) is for all rotten oranges in the queue right?