Longest Consecutive Sequence | Google Interview Question | Brute Better Optimal

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

КОМЕНТАРІ • 329

  • @takeUforward
    @takeUforward  11 місяців тому +13

    Please watch our new video on the same topic: ua-cam.com/video/oO5uLE7EUlM/v-deo.html

    • @ANONYMOUS-ir8xq
      @ANONYMOUS-ir8xq 8 місяців тому

      striver i am totally confused with the time complexity in optimal approach to find an element in set we need only o(1)??

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

      in brute force approach time complexity is O(n^3)

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

      one for for loop second may be maxi subarray is n and third for linear search

    • @jeevankurian9148
      @jeevankurian9148 15 днів тому

      @9:45 It was like Raj is showing middle finger to us😂.

  • @shubhanshusharma7457
    @shubhanshusharma7457 Рік тому +65

    this person deserves lot of respect for giving such a content for us free of cost. massive respect for you bhai.

  • @sontujain7851
    @sontujain7851 8 місяців тому +21

    The best part is that you just know that you solved the question just after raj draws the diagram. Amazing!!

  • @lingasodanapalli615
    @lingasodanapalli615 Рік тому +55

    I think the brute force is not equal to N*N. But it is N*N*N. Because for every outer loop the inner loop will be traversed N*N times.

  • @sumanthvarma1908
    @sumanthvarma1908 Рік тому +66

    I believe that you #striver will remain forever in the hearts of lakhs of students around the world ❤
    You are more than virat kohli for me because no one can come closer to your selflessness regarding contribution to the community
    Two people are my inspiration in this world #Virat #Striver
    For your HardWork and dedication

    • @yowaimo890
      @yowaimo890 7 місяців тому +3

      bhai wo zinda h

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

      🤣🤣@@yowaimo890

  • @lucygaming9726
    @lucygaming9726 5 місяців тому +12

    For anyone following the SDE Sheet, solve all problems of Disjoint Set Union (DSU) in Graph Series first.
    This question can be easily solved using DSU and very easy to come up too.
    Again, thanks to Striver for creating an awesome Graph playlist.

  • @ritikshandilya7075
    @ritikshandilya7075 4 місяці тому +5

    Literally the best content available in youtube , it really beats paid content.

  • @prabhagaikwad4849
    @prabhagaikwad4849 Рік тому +29

    I implemented the brute force first, the time complexity is O(n^3) as we need to start over the search for every found consecutive number. As array may be in sorted order.

    • @tusharvlogs6333
      @tusharvlogs6333 Рік тому +5

      glad i found this. was also thinking the same how can it be n^2 . because like if we have 104,101,102,103. so for 101 i need to check the whole array again then when i reach 103 again from starting .

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

      @@tusharvlogs6333 For every element you are traversing the whole array , to traverse each element it is O(N) and for each element you are traversing the array again so another O(N) , i.e., O(N^2)

    • @ShivamSingh-gk3qu
      @ShivamSingh-gk3qu Рік тому +6

      @@yugal8627 its O(N^3) bro just do dry run

    • @krishanubiswas6869
      @krishanubiswas6869 8 місяців тому

      thanks for the confirmaton...i was also thinking that...striver may have forgotten to take into account the time complexity of the linear search part....

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

      int longestSuccessiveElements(vector& a) {
      sort(a.begin(), a.end());
      int n = a.size();
      int maxCount = 1, c = 1;
      for (int i = 1; i < n; i++) {
      if (a[i] == a[i - 1] + 1) {
      c++;
      maxCount = max(maxCount, c);
      }
      else if (a[i] != a[i - 1]) {
      c = 1;
      }
      }
      return maxCount;
      }
      more simple app

  • @leoved1073
    @leoved1073 Рік тому +32

    ** Timestamps **
    0:00 Introduction
    0:52 Explaination of problem.
    1:48 Brutforce approach
    4:01 Code
    5:21 Better approach
    10:30 Code
    12:56 Optimal approach
    18:35 Code

  • @takeUforward
    @takeUforward  Рік тому +61

    Let's march ahead, and create an unmatchable DSA course! ❤
    Use the problem links in the description.

    • @leoved1073
      @leoved1073 Рік тому +14

      Idk why did you upload this video again but if you did just because better solution had edge case of multiple duplicate elements then hats off to you man ❤ even though it was negligible mistake still you re-recorded that part and uploaded video again I really appreciate your efforts 🫂

    • @takeUforward
      @takeUforward  Рік тому +19

      Yess that was the reason

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

      Understood

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

      Thank you brother for this DSA 💥💥course

  • @yourstrulysidhu
    @yourstrulysidhu Рік тому +5

    Finally found the explanation of the while loop time complexity. Thanks!

  • @infernogamer52
    @infernogamer52 Рік тому +7

    Whenever your heart is broken don't ever forget you're golden💯

  • @thebishalpaul
    @thebishalpaul Рік тому +8

    correction 13:44 hashset in java also doesn't order elements

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

    Amazing work.... I will complete the whole series....

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

    when I saw this video update today, I was like what, wasn't it uploaded yesterday 😂

  • @vaibhavpratapsingh9956
    @vaibhavpratapsingh9956 Рік тому +10

    i think the complexity for the first brute force would be O(n^3)

  • @meghasharma4875
    @meghasharma4875 12 днів тому

    i directly got better approach in mind

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

    Understood! Awesome explanation as always, thank you very very much for your effort!!

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

    Understood. Amazing. Keep going mate.

  • @paritoshmalhotra6309
    @paritoshmalhotra6309 Рік тому +11

    We can use unordered_map to replace the Linear Search in the brute force solution to bring down it's complexity to O(n^2).

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

      And we can also use sorting to reduce it to nlogn time complexity

    • @GOJOANDSUKUNAFAN
      @GOJOANDSUKUNAFAN 2 місяці тому

      ​@@calisthenics5247 yes correct I used hashing tho 😭

  • @CodewithKing360
    @CodewithKing360 2 місяці тому +2

    You understood brutforce and better very well but i do not understtod optimal

  • @ksankethkumar7223
    @ksankethkumar7223 Рік тому +64

    I guess the brute force technique will take O(N^3) and not O(N^2) because for every element we have to linear search until we break out of the longest sequence

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

      Nice observation!

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

      That comes under a manually defined function which will not be counted in the loop and would have an another O(n) TC ...as per my observation 🧐

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

      @@RajeevCanDev It will run in the loop even though it is user defined function and hence TC boils down to N^3

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

      @@ksankethkumar7223 yeahh true👍🏻, but may be there is an another logic by which striver stated it as TC O(N²) or maybe he is wrong

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

      @@RajeevCanDev idk about that but the approach he mentioned is O(N^3)

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

    Thank you striver , Very well explained and Time complexity part was amazing.

  • @shubhamagarwal1434
    @shubhamagarwal1434 17 днів тому

    #Free Education For All.. # Bhishma Pitamah of DSA...You could have earned in lacs by putting it as paid couses on udamey or any other elaerning portals, but you decided to make it free...it requires a greate sacrifice and a feeling of giving back to community, there might be very few peope in world who does this...."विद्या का दान ही सर्वोत्तम दान होता है" Hats Off to you man, Salute from 10+ yrs exp guy from BLR, India.....

    • @aryanchauhan2571
      @aryanchauhan2571 8 днів тому

      Say that again, after you discover something called “TUF+”

  • @amansrivastava1232
    @amansrivastava1232 2 місяці тому

    In my opinion, the time complexity for the brute force solution would be O(n^3)

  • @SAROJKUMAR-xe8vm
    @SAROJKUMAR-xe8vm 7 місяців тому +2

    If I can not be the part of the sequence then I will be the new sequence.

  • @user-ke7fs7ds6h
    @user-ke7fs7ds6h 7 місяців тому +1

    awesome videos, but one correction like in brute force approach the time complexity should be o(n^3) , rest everything is perfect.

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

    Time complexity explaination in depth by yours after every explaination of problem is really really helpful that i love the most. And better and optimat solution here is really cool. I solved better solution by myself before watching your tutorial. Thankyou Striver

  • @kajiazadali7738
    @kajiazadali7738 Рік тому +6

    brute force solution t.c : O(N^3) ?

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

    Great Explanation

  • @joelpappachan7853
    @joelpappachan7853 5 місяців тому

    You might be the GOAT of DSA

  • @culeforever5408
    @culeforever5408 10 місяців тому +2

    understood 🎯

  • @kroax9720
    @kroax9720 19 днів тому

    Life Changing 💕💕

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

    Understood🎉
    40 lakh

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

    the better solution was not working on coding ninja so i just want to update the code and show the code which was working!
    int longestSuccessiveElements(vector&a) {
    if (a.empty()) {
    return 0; // Return 0 for an empty vector
    }
    std::sort(a.begin(), a.end());
    int n = a.size();
    int longest = 1;
    int count = 1;
    for (int i = 1; i < n; i++) {
    if (a[i] == a[i - 1] + 1) {
    count++;
    } else if (a[i] != a[i - 1]) {
    count = 1;
    }
    // Update the longest length
    longest = std::max(longest, count);
    }
    return longest;
    }

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

    Your video is very helpful for everyone, thank you ❤

  • @surbhirathore._
    @surbhirathore._ 2 місяці тому +1

    What's wrong in this code! It's working for half test cases not all
    Int n = a.length;
    Int largest = 1;
    for(int I=0 ; I

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

      bro it should be i

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

    I think this solution will never come in mind of someone who didn't seen this type of problem.

  • @pavansai2859
    @pavansai2859 5 місяців тому

    this is GOD level man!! Thank you!!

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

    Amazing explanation❤️

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

    Using treeset would also be a better solution, as adding elements into treeset takes nlogn time and then parsing and checking is easy after that

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

    Understood ❤

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

    us, really a good one in TC Explain

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

    Hi Raj, the TC for the BF solution should be O(n^3) and not O(n^2) since there are 3 nested loops and inner while loop will run for nearly n times and same goes for the function that does the linear search.

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

    the time complexity for insertion in set is O(logN) so the time complexity for this algo will be O(NlogN)

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

      no its unordered set

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

      For unordered_set the time complexity of every operation in set is O(1). So, after N operations the TC will be o(N) in the best and average case and O(N^2) in the worst case if collision happens.

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

    Very well explained, brother. Thank you

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

    Fantastic Explaination..!

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

    python optimal solution:
    longest=1
    hashmap={}
    count=0
    n=len(arr)
    for i in range(n):
    num=arr[i]
    hashmap[num]=1
    for j in range(n):
    num=arr[j]
    count=1
    while num+1 in hashmap:
    count+=1
    num+=1
    longest=max(longest,count)
    return longest
    i used hashmap to access the elements which will be taking o(1) complexity so o(n+n) will be time complexity and sc-->o(n)

  • @trojanhorse8278
    @trojanhorse8278 2 місяці тому

    @15:53 worst case time complexity of find operation in unordered_set is O(N) and average case is of O(1).

  • @shubhamdhiman5602
    @shubhamdhiman5602 10 місяців тому +2

    How the optimal solution is optimal, still taking O(n^2) and better solution takes only O(nlogn). Can anyone please explain this.

  • @cameye9
    @cameye9 3 місяці тому

    We can solve this question in O(N) Time Complexity and O(1) Space Complexity, by taking previous int arr[0] and comparing from index 1 to it's difference is either 0 or 1 if it is 0 continue and else if 1 increments count++ and update maxLen=Math.max(maxLen,count) and else count =1 and previous will be arr[i] current value. By that approach we can easily solve in O(N) time and O(1) space.🙂

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

    sir what do you mean when you say collision happens??? can you explain with example....

  • @NazeerBashaShaik
    @NazeerBashaShaik 4 місяці тому

    Understood, thank you.

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

    Understood. Thanks a lot

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

    I think we need to consider the time complexity of underlying data structure as well
    I mean if we are using set.find() then it not happens in O(1) time and we have not considered its time complexity...
    we can insted go for unordered map

  • @shreekarpasupuletia2269
    @shreekarpasupuletia2269 9 днів тому

    please write the ode for 1st and 2nd method also in coming videos

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

    Solution using map :
    class Solution {
    public:
    int longestConsecutive(vector& nums) {

    int n=nums.size();
    int cnt=0,longest=0;
    map mpp;
    for(int i=0;i

  • @JK-de2gh
    @JK-de2gh 14 днів тому +1

    understood

  • @ParasSharma-mf8or
    @ParasSharma-mf8or Рік тому +4

    This same video was uploaded yesterday also

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

    Understood Bhaiya!

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

    My approach for better solution :-
    #include
    using namespace std;
    int main()
    {
    vector v = {100,5,100,101,101,4,3,2,3,2,1,1,1,2};
    int n = v.size();
    sort(v.begin(),v.end());
    int longest = 1;
    int length = 1;
    for(int i =0; i 1 + v[i]) //if consecutive diff > 1 then reset count to 1
    {
    length = 1;
    }
    }
    cout

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

    Happy teacher's day striver ,
    Today is 5 th sep and i am watching this one

  • @tamilmukbang3789
    @tamilmukbang3789 4 місяці тому

    Understood. thank you

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

    Understood!

  • @nikhild.20
    @nikhild.20 10 місяців тому

    Instead of iterating in set, we can iterate in array as well, right?
    int longestSuccessiveElements(vector&a) {
    // Write your code here.
    setst;

    for(int i=0;i

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

      can you explain me bro why we using " == st.end() " and " != st.end()" ...... he used in many problems but i don't understood......

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

    very nice problem sir understood very nicely sir......

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

    i have solve this question from striver hash playlist still i am watching this video.

  • @sayantanpoddar5428
    @sayantanpoddar5428 9 місяців тому

    understood
    please came with String playlist sir

  • @sarthakkharade7112
    @sarthakkharade7112 5 днів тому

    understood sir

  • @MaheshPatil-of1zy
    @MaheshPatil-of1zy 4 місяці тому

    I think the brute force complexity is o(N^3).

  • @ali_dev7415
    @ali_dev7415 11 місяців тому +1

    Best better solution with edge cases:- O(nlogn)+O(n)
    class Solution {
    public:
    int longestConsecutive(vector& nums) {
    int n = nums.size();
    int count = 1;
    int maxx = 1;

    if (n == 0) return 0;

    sort(nums.begin(), nums.end());


    for (int i = 1; i < n; i++) {
    if (nums[i] == nums[i-1] + 1) {
    count++;
    maxx = max(count, maxx);
    } else if (nums[i-1] == nums[i]) {
    continue;
    } else {
    maxx = max(count, maxx);
    count = 1;
    }
    }

    return maxx;
    }
    };

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

    as usual, awesome

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

    Understood🔥

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

    Understood ❤️

  • @hardikpatel352
    @hardikpatel352 5 місяців тому

    if(striver(Raj sir) == legend ) ans ="true";
    else ans = "Yes Striver(Raj sir) is LEGEND";

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

    Please, please, please if you find this video useful. Like. It is just a click away

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

    Understood, thanks :)

  • @heyOrca2711
    @heyOrca2711 4 місяці тому

    Understood! Sir

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

    Understood✅🔥🔥

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

    This is O(N^2) solution, better to sort the array. '

  • @himadriroy7980
    @himadriroy7980 9 місяців тому

    Edge cases are the worst nightmares of coders.

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

    Can anyone explain if(st.find(it-1)==st.end()) && if(st.find(x+1)!=st.end())

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

      First element ka previous search kar raye hai agar vo == end ho Gaya matlab vo nahi ha set ma this means it is 1st ele otherwise vo 1st ele nahi hoga

  • @HARSHA_27
    @HARSHA_27 9 місяців тому

    Understood!!🙇‍♂

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

    Understood

  • @RohitRaj-kr7ti
    @RohitRaj-kr7ti Рік тому +1

    Hey,
    The complexity in brute force is N^3, as there is a linear search too.
    In the optimal code, one point that can be corrected is that while you say that we will iterate over set but essentially you end up reiterating the input array again.. I would request to use the set numbers only, convert them to array and then use it only.
    int[] numsFromSet = hashSet.stream().mapToInt(Integer::intValue).toArray();
    @takeUforward

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

      Why are you converting the hashSet to an array? This operation takes another O(set size) for unboxing the elements. And you have no other option other than linear search to search for consecutive elements using the array approach.
      Use the set.contains() while iterating through the set itself.

  • @WolfMan-z8k
    @WolfMan-z8k 20 днів тому

    Understand

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

    Understood Bhai

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

    Understood Sir!

  • @juhichoudhary9281
    @juhichoudhary9281 9 місяців тому

    Understood❤️‍🔥

  • @HuzaifaBilal-fo7zc
    @HuzaifaBilal-fo7zc Рік тому

    When you write code in editor make sure to zoom in

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

    Understood 💯💯💯

  • @mr_weird3680
    @mr_weird3680 3 місяці тому

    Thanks Brother

  • @per.seus._
    @per.seus._ Рік тому +1

    understood❤

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

    We can even do last one with O(n) with even worst case

  • @user-is6ky7pp2n
    @user-is6ky7pp2n 3 місяці тому

    Understood !!

  • @user-kd7ld4ff4t
    @user-kd7ld4ff4t 6 місяців тому

    Thank you

  • @HR-pz7ts
    @HR-pz7ts 4 місяці тому

    what if all size of list is n and all elements are distant to each other by a difference of 2. Meaning the longest consecutive subseq is 1. Then this algo is taking TC of n^2

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

    I understood this problem.

  • @ShivamSingh-gk3qu
    @ShivamSingh-gk3qu Рік тому +1

    107,106,105,104,103,102,101,100
    for this case the time complexity even using Hashset will be O(N^2+N),
    bcoz if we are using unordered set then we have iterate from 107 to 100 and when we reach 100 then again we'll iterate using while loop to get the longest sequence.
    Someone plz correct me if i am wrong ........

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

      No, it is not the case
      as we are firstly iterating from 107 to 101 and as these are not the first element, while loop will never run
      while the loop will run for 100 only
      So, we are only iterating the whole array again for 100, not for all the cases

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

      you are missing if condition, if 107 is not the starting element then while won't run

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

    Why we don't use an array of frecvente, also can use and bitsed for memories, complexity will be O(n*max) max mean the maximum number, and we read n number and after with for we go through maximum number

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

      Bitset b;
      Int maxi;
      Int main(){
      Int n;
      For(int i=1;i>x; b[x] = 1;
      If( x > maxi ) maxi=x;
      }
      Int length=0,cnt=0;
      For(int i=1;i length) length = cnt;
      If( b[i] == 0) cnt = 0;
      }
      Cout