Longest Consecutive Sequence | Leetcode(Hard) | GooGLe

Sdílet
Vložit
  • čas přidán 26. 07. 2024
  • Please watch the new video which covers it in more depth, and also prints it: • Longest Consecutive Se...
    Check our Website:
    In case you are thinking to buy courses, please check below:
    Link to get 20% additional Discount at Coding Ninjas: bit.ly/3wE5aHx
    Code "takeuforward" for 15% off at GFG: practice.geeksforgeeks.org/co...
    Code "takeuforward" for 20% off on sys-design: get.interviewready.io?_aff=takeuforward
    Crypto, I use the Wazirx app: wazirx.com/invite/xexnpc4u
    Take 750 rs free Amazon Stock from me: indmoney.onelink.me/RmHC/idje...
    Earn 100 rs by making a Grow Account for investing: app.groww.in/v3cO/8hu879t0
    Linkedin/Instagram/Telegram: linktr.ee/takeUforward
    ---------------------------------------------------------------------------------------------------------------------------------------------------- I have decided to make a free placement series comprising of video lectures(C++ and Java) on the entire SDE sheet.. ✅(bit.ly/takeUforward_SDE) ..
    ✅Checkout Unacademy's CP(Apply coupon "TAKEUFORWARD"): unacademy.com/goal/competitiv...
    ✅Use coupon-code "TAKEUFORWARD" for getting 10% for all GFG courses: practice.geeksforgeeks.org/co...
    ✅Entire Series: • Two Sum Problem | Leet...
    ✅Problem link: leetcode.com/problems/longest...
    If you appreciate the channel's work, you can join the family: bit.ly/joinFamily
    Thumbnail Creator: / rikonakhuli
    Striver's Linkedin Profile: / rajarvp
    Instagram: / striver_79
    Connect with us: t.me/Competitive_Programming_tuf (Use Link in Mobile only, if not works search "takeUforward" in telegram)..
    #dsa #leetcode #placements
  • Krátké a kreslené filmy

Komentáře • 418

  • @takeUforward
    @takeUforward  Před 3 lety +63

    Please watch the new video which covers it in more depth, and also prints it: czcams.com/video/oO5uLE7EUlM/video.html
    Understooooooooooooooood?
    .
    Instagram(connect if you want to know how a SDE's normal life is): instagram.com/striver_79/
    .
    .
    If you appreciate the channel's work, you can join the family: bit.ly/joinFamily

    • @takeUforward
      @takeUforward  Před 3 lety +12

      @RAJVEER Singh video release hua hi nai h XD

    • @BatMAn-kq3zf
      @BatMAn-kq3zf Před 3 lety

      sir please create internship roadmap for people who have wasted first year i.e have 1 year left

    • @abhinavmishra7617
      @abhinavmishra7617 Před 3 lety

      yuppppppppppppppp!
      ek baar me hi smjh aa gaya dono approach....awesome bro....thanks!

    • @sahilchoudhary1473
      @sahilchoudhary1473 Před 3 lety

      yes

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

      instead of using set count(), i did find() method and the time complexity heavily increased. Also, why cant we use map or vector instead of set

  • @vishal_rex
    @vishal_rex Před 2 lety +102

    I have a doubt. Let's take a test case: [3,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
    While loop won't execute for 3 & 2 since 1 is present. But while loop will be executed for 1 since 0 is not present, and that will be executed (n-2) times here.
    I think instead of iterating over nums which consists repeated elements, we can iterate over hashset then for 1 it will execute while loop only once resulting time complexity O(n) + O(n)

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

      This is a really good point, Thanks!

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

      Agreed. On Leetcode just this small change made it much more faster.

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

      Valid Point

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

      how inserting n elements takes O(n) time? in set insertion takes logn time so it should be nlogn then it is no better than just sorting and linearly checking

    • @mohsinhusain4
      @mohsinhusain4 Před 2 lety +12

      @@rishavgupta7868 Use unordered set.

  • @AnkitMishra-mz4xt
    @AnkitMishra-mz4xt Před 2 lety +58

    If you are getting TLE, just declare it as unoredered_set it will pass

    • @kartiksuman9814
      @kartiksuman9814 Před 2 lety

      Bhai it really worked....but what's the reason behind this?

    • @kartiksuman9814
      @kartiksuman9814 Před 2 lety

      Bhai it really worked....but what's the reason behind this?

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

      @@kartiksuman9814 Accessing element is faster in unordered set , costs O(1), but in orderd set, its O(log n)

    • @kartiksuman9814
      @kartiksuman9814 Před 2 lety

      Okay... thankyou

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

      @@kartiksuman9814 tc of set is O(nlog) because it sorts the elements, but for unordered_set, its O(n)

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

    It will give tle on leetcode. Use this instead
    int longestConsecutive(vector& nums) {
    unordered_set s;
    for(int i=0;i

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

      Thank u ❤

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

      bro i did get tle but idk why ??? can you tell why it gives tle

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

      @@shikharmalik3787 The time complexity will be O(n^2). So TLE

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

      i used unordered map instead of set, it runs but is very slow compared to set, why?

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

    after watching the intution i have coded it myself, way of your teaching is magic. i am feeling the improvment. Thanks a lot

  • @gauravraj2604
    @gauravraj2604 Před 2 lety +6

    Deciding at the last that time complexity of given solution is actually ~O(n) was really challenging. Thanks Striver for this explanation.

  • @sidhaantgupta1974
    @sidhaantgupta1974 Před 2 lety +26

    The hashset solution is actually slower in practice than the sorting one

    • @sourin.majumdar
      @sourin.majumdar Před rokem

      sorting one takes around 15 ms on avg but the set one is takinh 800+ ms

    • @MrHip4hopper
      @MrHip4hopper Před rokem +1

      @@sourin.majumdar exactly its O(n2) actually

    • @anurondas3853
      @anurondas3853 Před rokem +3

      Guys the absolute run time actually depends upon a lot of different things than your algorithm complexity. It happens many times that an n squared solution runs faster than an n solution, but this doesn't mean that O(n^2) is suddenly better than O(n). Striver actually talked about it before.

    • @amansinghal4663
      @amansinghal4663 Před rokem

      ​@@anurondas3853 Yes you are right. Also particularly in leetcode, the time it shows after the solution gets accepted cannot be used to judge the actual time taken by an algorithm. It's just comparing our algorithm's running time with running time of those who have submitted it earlier. It may happen that when i am running my code, the leetcode's servers are running slower than usual and hence it took more time than others code.
      I have noticed one very interesting thing about this in leetcode.
      After a leetcode contest, if you try to submit a solution for any of that contest's question, then even if you write a O(n^2) solution, leetcode will tell that it is faster than 100% because it is a new question and it has not been submitted by many users till now.

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

    Nice explanation Striver bhaia .. thanks for making this series .. each and every question helps me to get more better in data structures 😍

  • @ritesh1211
    @ritesh1211 Před 2 lety +12

    Yes it does give TLE just replace nums with hashSet in second for loop
    I.e
    for(int num: hashSet) not
    for(int num: nums) this will make complexity to o(n) he missed this by mistake

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

      thanks bro

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

      could you also tell what to correct in the 4sum problem,it is giving runtime error

    • @amitarya4894
      @amitarya4894 Před 2 lety

      thank you so much buddy, it works now

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

      @@yatin3699 Inside the second loop (j loop), for calculating target2 use "long long" instead of using "int", this will solve the issue.

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

      But what is the difference? Both nums and hashSet are having same element? Why it is giving TLE with nums and not with hashset? Please can you explain

  • @Rahul0508-n9m
    @Rahul0508-n9m Před 3 lety +3

    Thats what i call a brilliant explanation 🙏

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

    Brilliant Approach....I actually solved the question by counting forwards and to reduce time complexity, I stored previously counted length from that point. Damn, I should have also thought of doing backward count check ....

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

    Hi,
    Thanks a lot for helping us. I try to understand the concept and try to implement. So here is Naive Solution in python,
    class Solution(object):
    def longestConsecutive(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    if(len(nums) > 0):
    le = 0
    cle = 0
    nums.sort()
    print(nums)
    for i in range(0, len(nums)-1):
    curr = nums[i]
    nxt = nums[i+1]
    if((curr) == nxt):
    cle = cle
    elif((curr + 1) == nxt):
    cle += 1
    else:
    le = max(cle,le)
    cle = 0
    le = max(cle,le)
    return le + 1
    else:
    return 0
    Optimal Solution in python
    class Solution(object):
    def longestConsecutive(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    "pushing every thing into the set"
    elements = set()
    longest = 0
    for i in range(0, len(nums)):
    if nums[i] not in elements:
    elements.add(nums[i])
    "now we need to check if the element is present in the set or not"
    for i in range(0, len(nums)):
    flag = True
    val = 1
    if((nums[i]-1) not in elements):
    while flag == True:
    if((nums[i] + val) in elements):
    val += 1
    else:
    flag = False
    longest = max(val, longest)

    return longest

  • @codingachinilgtifirbhikrrh9009

    1 doubt : the time complexity will not be O(N), if it contains duplicate elements in significant numbers(n-1,n-2 etc) beacuse then it will loop for every duplicate elements and it will b order of O(N^2)

    • @maitreyikshetrapal1644
      @maitreyikshetrapal1644 Před rokem +3

      but we are using set..so it will eliminate duplicate elements

    • @shashanksrivastava7262
      @shashanksrivastava7262 Před rokem

      sets doesnt contain duplicate values

    • @VishalGupta-xw2rp
      @VishalGupta-xw2rp Před rokem

      Set won't store duplicates but I think what he is trying to say is that if the array itself contains duplicates then we will be checking that minimum number again and again and again.
      This question will work fine if the array itself doesn't contain any duplicates

    • @sasidharnaidu4507
      @sasidharnaidu4507 Před rokem

      ​@@VishalGupta-xw2rp even if array contains, duplicate elements, the order won't change to O(N2).

  • @mdaffan1650
    @mdaffan1650 Před rokem +4

    we can actually iterate through the set as the set is having sorted elements and can get to the solution
    and it will also be O(n) solution

  • @fromdjangoimport__help__3585

    if u r getting error use this simple solve -- sets;

    for(int i=0;i

  • @joydeeprony89
    @joydeeprony89 Před 2 lety

    so smooth and crystal clear explanation.

  • @prasantharavindramesh1078

    bro fantastic explantion as always.I just have couple of doubts.
    1.Can i extend this code when all array elements are negative.?..
    2.Do we need to include cases like if there are no elements in array then just return 1 for the length and if there 0 elements return 0.
    Thanks bhaiya.All the videos have awesome explantions.
    Thank you so much for making these videos

  • @adityadixit5631
    @adityadixit5631 Před 3 lety

    Thank you for explaining the time complexity, why Time Complexity = O(n) is real key

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

    use an unordered map insert all of the values as keys and set the key's values to 0.When you iterate through the map,set the values of the keys equal to 1 when you have checked the value so that you know the next time you have look for it that it has been checked.

    • @divyareddy7622
      @divyareddy7622 Před rokem

      how is this useful in this problem? i didnt understand

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

    Literally you are doing great ✌

  • @RahulSingh-de6tb
    @RahulSingh-de6tb Před 3 lety +6

    Your way of approaching a solution is amazing and is sufficient enough to build own solution. without looking into code, that's the beauty of your channel.
    Thanks!!
    btw you mistakenly written set instead of unordered_set.

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

    The explanation is really great

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

    absolutely loved the intuition

  • @preetikushwaha8734
    @preetikushwaha8734 Před 3 lety

    the best explanation ever! thank you

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

    UNDERSTOOD...!!!
    Thanks, striver for the video... :)

  • @adityapandey8245
    @adityapandey8245 Před 3 lety

    Thanks Bhai!! understood the algorithm and solved in a jiffy

  • @avnishsingh1538
    @avnishsingh1538 Před 3 lety +3

    the explanation is great

  • @tanyacharanpahadi158
    @tanyacharanpahadi158 Před 3 lety +13

    maze aa gaye. after knowing the approach its difficult to believe that this question comes under hard category. Thank you striver really missed you.

  • @krsingh.shubham
    @krsingh.shubham Před 3 lety +5

    finally... ! cant ask for more, but good and more helpful if we get atleast two videos on the series.

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

    Brilliant explanation!

  • @agrajgarg2831
    @agrajgarg2831 Před 2 lety +36

    After striver posted this video, the difficulty of this question got reduced to medium. Power of striver.

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

      its actually just a simple application of hash sets, shouldn't it be easy

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

      @@mannthakkar the concept is easy but the implementation is a lil bit tricky

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

    if we add just visited map , time can be reduced by 800ms .
    unordered_map mp,vis;
    for(auto num:nums)
    mp[num]=1;
    int ans=0,cnt;

    for(auto num:nums)
    {
    cnt=0;
    if(vis[num]==0&&mp.find(num-1)==mp.end())
    while(mp.find(num)!=mp.end())
    cnt++,vis[num]=1,num++;
    ans=max(ans,cnt);
    }
    return ans;

  • @GauravSingh-le8mq
    @GauravSingh-le8mq Před 2 lety

    hey, 1 thing I wanted to ask, if we can sort the array in linear time, I mean.....they have given the range of numbers from -10^9 to 10^9 so digits are constant so radix sort + bucket sort for each digit combined can sort the array in linear time correct? after that everything is straight fwd, correct? let me know if I am missing something.

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

    1.Insertion in a set takes O(log(n)) time ,
    2. we are inserting all the elements so we have N elements to enter
    3. Thus building the set itself will take O(N*log(N))
    how is the algorithm O(N) and not O(N*log(N))

    • @phoenix-be8ko
      @phoenix-be8ko Před 2 lety

      Same ques here

    • @nisargsheth5153
      @nisargsheth5153 Před 2 lety

      We are inserting in unordered_set or hashset which has insertion complexity of O(1).

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

      Inserting into a hashset takes constant time complexity O(1)

    • @shri9229
      @shri9229 Před 2 lety

      @@SwapnilSarkar Thank you , what you are saying absolutely made sense to me , in my comment I was talking about 12:48 where the cpp solution explained has a set rather than an unordered_set . So, that was my concern.

    • @shri9229
      @shri9229 Před 2 lety

      @@nisargsheth5153 @Swapnil Sarkar Thank you , what you are saying absolutely made sense to me , in my comment I was talking about 12:48 where the cpp solution explained has a set rather than an unordered_set . So, that was my concern.

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

    I stopped at 3:36 of your video and tried the problem and got AC . The moment you said it would be a hash set I got it. Now watching the whole video again after solving. Thank you sir.

    • @Yash_Parashar
      @Yash_Parashar Před 3 lety

      Bhai I am not getting brute force approach can you tell me???

    • @aniketbhoite7168
      @aniketbhoite7168 Před 2 lety

      @@Yash_Parashar brute force ...if you are sorting a vector ...it will take n logn

  • @adithyaharish3530
    @adithyaharish3530 Před 3 lety

    you are doing a great work :)

  • @manojgmanojg9600
    @manojgmanojg9600 Před rokem

    Wonderful Explanations, before watching this video,by question i sawn that, it is very hard and difficult to understand but after watching this video of striver bhaiya ,I understand that hard problem is very easy.

  • @omk2990
    @omk2990 Před 2 lety +6

    I'm still confused why Time complexity is O(3N), isn't it O(N) +O(N*N) ???

  • @imonraj
    @imonraj Před 2 lety

    Very nice videos.... Really appreciable

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

    bs bro. aaj dekh raha tha 'Striver' naam ka mouse GDocs mein moj kaat raha tha. pata chal liya tha video aane wali hai. Xor wale question pe video ayegi to real satisfaction milegi jindagi mein. Xor subarray wala karke depression ho lia. ty for support

    • @sen-th3xo
      @sen-th3xo Před 3 lety +1

      haan bhai XOR ka efficient solution ka video jaldi bro

    • @Zero-tu3ey
      @Zero-tu3ey Před 3 lety

      +1 on XOR video

    • @uravggymbro7338
      @uravggymbro7338 Před 3 lety

      "Count number of subarrays with given XOR" referring to this I think? Yeah I'd like a video for that

    • @ludrayn936
      @ludrayn936 Před 3 lety

      XOR question on Day 4 was supposed to clear problems not create more... XD Help would be appreciated

    • @johnson3049
      @johnson3049 Před 3 lety

      xor video nikalo bro jaldi waiting for it

  • @harshavardhanravada4509

    sir i think we need to use unordered map for time complexity of O(1)*n for going through entire loop other wise it will be O(nlogn)

  • @shubhankurkumar539
    @shubhankurkumar539 Před 3 lety

    Just in case someone needs brute force solution as discussed above
    class Solution {
    public:
    int longestConsecutive(vector& nums) {
    if(nums.size()==0) return 0;
    if(nums.size()==1) return 1;
    int n=nums.size();

    sort(nums.begin(),nums.end());
    vectorv;
    v.push_back(nums[0]);

    for(int i=1;i

  • @braggergamer4975
    @braggergamer4975 Před 2 lety

    just using a set to store the nums arr and using the 1st approach also gives us O(n) time and O(n) space (also runs faster on leetcode)
    here is the code...
    int longestConsecutive(vector& nums) {
    set s;
    if(nums.size()==0)
    {
    return 0;
    }
    for(int i=0;i

    • @manistrikes
      @manistrikes Před 2 lety

      complexity will still be o(nlogn) although the soln will be accepted since set uses o(nlogn) for storing n elements.

  • @zehrxsyed
    @zehrxsyed Před 3 lety

    you explain really well. thankyou;

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

    Solution is good but shouldn't the time complexity be O(n^2) as the while loop for finding the length of the sequence lies inside the for loop?

    • @manistrikes
      @manistrikes Před 2 lety

      No...finding any element in hash set requires o(1)..so o(n) for the consequetive sequence encountered and o(n) for the traversal and o(n) for initial insertion of elements in hashset thatswhy o(3n).

  • @easward
    @easward Před rokem +1

    doesn't insertion of N elements into an ordered Set takes n*log(n) time? also in worst case we are using contains function which takes log(n) time in n length iteration , not n*log(n) time now?

  • @adityagupta9719
    @adityagupta9719 Před 3 lety

    @striver please explain why this solution is also working
    'int longestConsecutive(vector &num) {
    unordered_map m;
    int r = 0;
    for (int i : num) {
    if (m[i]) continue;
    r = max(r, m[i] = m[i + m[i + 1]] = m[i - m[i - 1]] = m[i + 1] + m[i - 1] + 1);
    }
    return r;
    }'

  • @riddhisharma9582
    @riddhisharma9582 Před 3 lety

    Wonderful Bhaiyaa.. Pls iska union-find wala soln pe bhi thoda insight dedo

  • @navneetkushwaha1830
    @navneetkushwaha1830 Před 3 lety

    ❤️ great examplanation

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

    unordered_set takes average of O(1) time in insertionbut a set takes O(log n ) time. So we need to use unordered_set instead of set in c++

    • @shahjaysheeldipalbhai207
      @shahjaysheeldipalbhai207 Před 2 lety

      yes he told hash set ,so it is same as unordered set.

    • @SlapB0X
      @SlapB0X Před rokem

      We can do 2 things:
      1. Insert into ordered map - O(logN) - and access elements which is O(1).. overall time complexity - O(NlogN)
      2. Insert into unordered map - O(1) - and access elements which is O(logN) .. overall time complexity is still - O(NlogN)
      i dont understand how either of these can be O(N)

  • @pravinyakumbhare4864
    @pravinyakumbhare4864 Před 2 lety

    Great work bhaiya
    int longestConsecutive(vector& nums) {
    unordered_mapm;
    int r=0;
    for(auto i:nums)
    {
    if(m[i])
    continue;
    r=max(r,m[i]=m[i-m[i-1]]=m[i+m[i+1]]=m[i+1]+m[i-1]+1);

    }
    return r;
    }

  • @nupurgarg6791
    @nupurgarg6791 Před 2 lety

    class Solution {
    public:
    int longestConsecutive(vector& nums) {
    sethash({nums.begin(),nums.end()});

    int longeststreak=0;
    for(int num:nums)
    {
    if(!hash.count(num-1))
    {
    int currentnum=num;
    int streak=1;
    while(hash.count(currentnum+1))
    {
    currentnum+=1;
    streak+=1;
    }
    longeststreak=max(streak,longeststreak);
    }
    }
    return longeststreak;
    }
    };
    it works

  • @122souravsinha5
    @122souravsinha5 Před 2 lety

    Nice explanation!!
    Just one doubt , doesn't inserting n elements in a set takes nlogn time.
    Please correct me if I am wrong.

  • @pritishpattnaik4674
    @pritishpattnaik4674 Před 2 lety

    Ver Nice Approach
    //optimized approach => tc - o(n), space - o(n)
    int longestConsecutiveOpt(vector &nums){
    set hashSet;
    for (auto x : nums){
    hashSet.insert(x);
    }
    int longestStreak = 0;
    for (auto x : nums){
    if (hashSet.find(x-1) == hashSet.end()){
    int currNum = x;
    int currStreak = 1;
    while (hashSet.find(currNum + 1) != hashSet.end()){
    currNum++;
    currStreak++;
    }
    longestStreak = max(longestStreak, currStreak);
    }
    }
    return longestStreak;
    }

  • @krishnavamsichinnapareddy

    Superb explanation 🔥

  • @varuntaneja7073
    @varuntaneja7073 Před 3 lety +3

    I think you used set instead of unordered_set in the c++ solution ......btw awesome video

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

      yeah it might have been, you can tell that to the interviewer does not matters that most.

    • @anshoorajput1413
      @anshoorajput1413 Před 3 lety

      yaa that will make the overall time complexity (nlogn)

  • @vipindhaka2333
    @vipindhaka2333 Před rokem

    Hi brother i tried both brute force and optimal approach that is using map in c++ and the brute force gives far less runtime than the optimal approach on leetcode
    What could be the reason

  • @gauravidesigns
    @gauravidesigns Před 3 lety

    Understood sir, Love You a thankyou sir

  • @akhileshgoswami7699
    @akhileshgoswami7699 Před 2 lety +9

    hey Stiver i want to ask you one question. in C++ code every time we are using count function of set , and time complexcity of count() in set is O(logN) then how dose the time complexcity of this algo could be O(N)
    it should to be O(Nlogn) correct me if im wrong? yha it's true that in java contains() use O(1) but in c++ count uses O(logn) so i think the time complexcity of C++ code should be O(nlogn) rather then O(N) it could be (N) if we use unordered_set coz the avarage cp of unordered_set of count function is (1) and wrost is O(N)

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

      yup i am thinking the same and leetcode m bhaia ka solution accept b ni hora we should use unordered set in case of c++!

  • @yashsrivastava5128
    @yashsrivastava5128 Před 2 lety

    if the element is in decresing order like n,n-1,n-2,,,5,4,3,2,1 then unitl element 2 we get all element-1 in a set .But at last the element we get 1 and 1-1=0 is not in set so we then check for 1->2->3->4->....->n so time complexity wont be O(n^2)?

  • @WhoSangItBetter
    @WhoSangItBetter Před 3 lety +3

    Great vid as always

  • @akshraj2197
    @akshraj2197 Před 3 lety +3

    Sir I have heard about c++ set is implemented in bst.
    So for inserting the value in to the set is nlogn then how complexity n
    And sorry if I'm wrong

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

      set(which is ordered ) is implemented from bst and unordered set is just a hash table same with map and unordered_map

    • @tejaswarambhe7464
      @tejaswarambhe7464 Před 3 lety

      @@jaydave2500 thanks for info

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

    How is it exactly O(N) algo ? Suppose when we check in the for loop if a number smaller then the number at current index of the array exists and there is no smaller number then a while loop will start which will start counting till we can't find a number which belongs to the current subsequence . So it will not be exactly O(n) right .So can someone please throw some light on this topic?

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

    Can you also talk more about the intuition behind the approaches used for solving this problem?

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

      I said that in the video, please watch it! I have mentioned about the intuition that I am looking to start from the minimum which is my intuition!

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

      @@takeUforward Oh, Yeah! Got it.

    • @decodingParinda
      @decodingParinda Před 3 lety

      @@jaynilgaglani9480 You could refer to my code explanation also.
      leetcode.com/problems/longest-consecutive-sequence/discuss/789257/Easy-Java-Solution-with-Explanation-O(N)

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

    Thank you sooooooo much bro!

  • @dhananjaysahu9076
    @dhananjaysahu9076 Před 3 lety

    What a simple approach it is but my tiny brain couldn't think about it 😭😭

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

    I just have feeling that unordered_map will slow the performance after some time due to collisions as Hashtable is its underlying ds. Better use bool array if n is bounded.

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

      Yes, just mention this in the interview it will work!

    • @casual_chess
      @casual_chess Před 3 lety

      Where is unordered_map used? I can see only set. And how can we use bool array instead. Please reply.

    • @akhilgupta3664
      @akhilgupta3664 Před 3 lety

      @@casual_chess U can use Hashmap with Key: Integer,value : boolean where value false means this is not the start of the consecutive sequence and value true means this is a start of the sequence. and run the loop only for that key where value is true i.e the start of the sequence, rest Logic is same !!

  • @avengerfirst1572
    @avengerfirst1572 Před 3 lety

    Solved it yesterday using hasmap

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

    It was nice explanation, I actually saw this solution on leetcode but didn't get the logic ,,but now I think this is so easy after watching your explanation
    Hey buddy Thanks

  • @ballisandeep3953
    @ballisandeep3953 Před 2 lety

    Amazing. Thank you Bhaiya

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

    how is the brute force solution faster than 75% of submissions on leetcode while the optimized is only 5%

  • @tarunboricha
    @tarunboricha Před rokem +1

    insted of using set we can use unordered map to optimise code even more
    This is my code :
    unordered_map mp;
    int ans = 0;
    for(auto it:nums)
    mp[it] = 1;
    for(auto it:nums){
    if(!mp[it-1]){
    int n = it;
    int temp = 1;
    while(mp[n+1]){
    n++;
    temp++;
    }
    ans = max(ans, temp);
    }
    }
    return ans;

  • @vaidviyogi4048
    @vaidviyogi4048 Před 2 lety

    By iterating the set in cpp
    class Solution {
    public:
    int longestConsecutive(vector& nums) {
    if(nums.size()==0){
    return 0;
    }
    set s;
    for(int i=0;i

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

    How is the time complexity O(N),if N is large then there can be many sequences right? So inner while loop will be executed multiple times,wont it it affect time complexity?

    • @manistrikes
      @manistrikes Před 2 lety

      but the inner while loop executes only once for any subsequence thereby adding t=o(n) to complexity...suppose we have 2 ,3 ,4 ,1,101,200,102,103
      we will have while loop running for the starting of sequence (1,2,3,4) from 1 and (101,102,103) from 101 i.e n times only in the entire length of hashset...It wont run from (2,3,4) nor for(3,4) nor for(102,103)....Hope this helps

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

    In gfg, a solution with priority queue is also there. What if the interviewer asks me to discuss that approach too?

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

      In the priority queue, insertion operation takes O(logn) complexity, so inserting n elements will take O(nlogn) and it's mentioned that t.c. should be O(n).

  • @rudrasimhaa269
    @rudrasimhaa269 Před 3 lety

    Thank you brother

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

    Getting TLE on leetcode if we use set but not with unordered_set.can anyone explain why?

    • @anjalis8483
      @anjalis8483 Před 2 lety

      Because set works in O(logN) complexity, unordered_set in O(N)

  • @priyadarsinipaikaray6271

    awesome explanation !!!😍

  • @harshdasila6680
    @harshdasila6680 Před rokem +1

    how can this test case have a output of 3: [1,2,0,1]

  • @fahrenheit2109
    @fahrenheit2109 Před 2 lety

    after watching this video, leetcode set this questions difficulty to medium.

  • @neyovyas3992
    @neyovyas3992 Před 3 lety

    Nice explanation

  • @linguisticgamer
    @linguisticgamer Před rokem

    More optimised way:
    public int longestConsecutive(int[] nums) {
    Set set = new HashSet(nums.length);
    int count = 1;
    int maxCount = 0;
    for(int i = 0; i < nums.length; i++){
    set.add(nums[i]);
    }
    for(int i = 0; i < nums.length; i++){
    if(set.contains(nums[i])){
    boolean run = true;
    int forward = nums[i] + 1;
    int backward = nums[i] - 1;
    count = 1;
    while(set.contains(forward)){
    set.remove(forward);
    forward++;
    }
    while(set.contains(backward)){
    set.remove(backward);
    backward--;
    }
    maxCount = Math.max(maxCount, forward-backward-1);
    }
    }
    return maxCount;
    }

  • @prakharagarwal6237
    @prakharagarwal6237 Před 3 lety

    You are awesome!!

  • @debugagrawal
    @debugagrawal Před 2 lety

    bhaiya ye lo more cleaner code poora logic in ~3 lines and easy to understand
    streak=1;
    int currentNum=num;
    if(subseq.find(num-1)==subseq.end())
    while(subseq.find(currentNum++)!=subseq.end())
    longestStreak=max(longestStreak,streak++);;

  • @joseph2073
    @joseph2073 Před 3 lety

    Thnku so much bhaiyaa 💖💖💖

  • @sauparnagupta5875
    @sauparnagupta5875 Před 2 lety

    doesn't set have logn complexity for insertion and access(c++ code)?

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

    Will it work if numbers in array are repeated??

  • @ujjwalmittal3785
    @ujjwalmittal3785 Před 3 lety

    I guess there is a need to erase elementd from unordered set also otherwise time may reach upto n2 .
    Let's suppose when have n/2 elements forming a sequnece and n/2 elements repeated .
    Eg
    9,8,7,6,5,4. N/2 elements
    And reamining n/2 as 4,4,4,4,4,
    This will go upto n2 time complexity

    • @takeUforward
      @takeUforward  Před 3 lety

      No, try to do it properly, i have showed an example in the explanation

    • @ujjwalmittal3785
      @ujjwalmittal3785 Před 3 lety

      @@takeUforward
      On submitting code time showed 552 ms in leetcode and as soon as I added a line of erase ,time got reduced to 12 ms .
      The logic is absolutely same , but the line is added keeping duplicate elements in mind

    • @takeUforward
      @takeUforward  Před 3 lety

      Watch out the video about how to use leetcode on other channel striver to understand its not the case. Try writing a cnt++ to count the number of operations, you will have a better idea

  • @om_1_2
    @om_1_2 Před 3 lety

    Understood bro👍👍👍

  • @bhushanpatil2601
    @bhushanpatil2601 Před 2 lety

    good work bro... HAPPY!!

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

    @take U forward sir, how the optimal solution code run in O(N) time complexity, since inside for loop you run a while loop and if the longeststreak is of length 1 when for every element you run while loop then time compexity comes out to be O(N^2)

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

      Nah, count the iterations the inner loop does not always runs for N time, observe carefully..

    • @mohammedmoin7888
      @mohammedmoin7888 Před 2 lety

      @@takeUforward sir I had the same query .thanks for answering it 👏👏👏👏

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

      @@takeUforward How do you say that? Even the inner while loop run m times (m

    • @AmitSingh-ut4wt
      @AmitSingh-ut4wt Před 2 lety +1

      @@roberttguo606 I also has the same doubt for the worst case the while loop will run for n times. Then the complexity will be O(N^2). The question also did not mention the longest consecutive sequence length whether it is less than n or not. Please @take U forward or anyone can clear this doubt

  • @itsarAnkit
    @itsarAnkit Před rokem

    how the time complexity is O(n) as insertion on map takes log(n) time and for n size array time will be O(nlogn)

  • @sanyamraina9878
    @sanyamraina9878 Před 2 lety

    wouldn't the time complexity be in nlogn (in C++)?
    The insert() function takes logn to insert the element

    • @sanyamraina9878
      @sanyamraina9878 Před 2 lety

      and in leetcode, there is a huge difference in time taken, the sorting is taking time around 150ms, whereas the HashSet is taking more than 2000 ms

  • @ankitkumaryadav562
    @ankitkumaryadav562 Před 3 lety

    Time complexity to O(nlogn) Hoga because inserting the element in set it takes long(n) time if we insert N element it takes Nlog(n)

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

      Unordered set average case me O(1) me chal jaata. But the worst case of unordered is o(N)..

    • @ankitkumaryadav562
      @ankitkumaryadav562 Před 3 lety

      @@takeUforward Thank you Bhaiya for clarification :)

  • @Tommyshelby602
    @Tommyshelby602 Před rokem

    int longestConsecutive(vector& nums) {
    unordered_set st;
    int n = nums.size();
    for(int i=0;i

  • @ankitbaiskhiyar3106
    @ankitbaiskhiyar3106 Před 2 lety

    we can use unordered_map for less ms

  • @ankitgoyal8556
    @ankitgoyal8556 Před 2 lety

    Great one.

  • @sagardas4569
    @sagardas4569 Před 3 lety

    Really amazing love you love you love you vaiya😋😍😍

  • @hardikagarwal7652
    @hardikagarwal7652 Před 3 lety +3

    Why aren't you directly iterating on the set?

    • @pruthvirajjadhav3853
      @pruthvirajjadhav3853 Před 3 lety

      for directly iterating we need to sort the array & it takes o(nlog) +o(n)to sort .
      by doing this we are getting o(n)+o(n)+o(n) which is o(n) finally
      But may be o(nlog) +o(n) would take less time than this .

    • @hardikagarwal7652
      @hardikagarwal7652 Před 3 lety

      @@pruthvirajjadhav3853 set is already in sorted order

    • @pruthvirajjadhav1996
      @pruthvirajjadhav1996 Před 3 lety

      @@hardikagarwal7652 check here 0:08

    • @hardikagarwal7652
      @hardikagarwal7652 Před 3 lety

      @@pruthvirajjadhav1996 when we store elements in the set then they are sorted

  • @infinioda108
    @infinioda108 Před 3 lety

    Thanks bro