Longest Consecutive Sequence - Solution | Hashmap and Heap | Data Structure and Algorithms in JAVA

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

КОМЕНТАРІ • 95

  • @sudiptasundar
    @sudiptasundar 2 роки тому +11

    Sir, your teaching method is just like Irrfan Khan's acting.
    It's just effortless.
    You make look difficult problems look easy to solve.
    Thank you.

  • @shishankrawat2105
    @shishankrawat2105 3 роки тому +9

    Its all love, love, and love 💖💖💖💖💖💖💖💖💖.
    I have never seen ur full video but, still able to solve problems. Do you know what does this means?
    It means that you are a great teacher and you explain things so simply. I just love it.
    Thank You 3000

  • @simrankak7045
    @simrankak7045 3 роки тому +6

    You make explaination look very very easy thanks much appreciated

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

    I was learning dsa in java and struggling in a hasmap . But after watching this video now able to solve the many problem using hashing.
    THANK YOU SO MUCH SIR...❤

  • @sanyamkothari4469
    @sanyamkothari4469 2 роки тому +1

    Sir u completes the definition of a teacher..🙇‍♀

  • @sachinsharma905
    @sachinsharma905 3 роки тому +5

    Thanks sir. Bahut accha kaam karte hai aap. The way with which you present your explanations
    and give sound logic for each is something which you only possess.

    • @Pepcoding
      @Pepcoding  3 роки тому +3

      Thank you for appreciating. and I am glad you liked it. I also hope that you are watching till end and trying to understand the what, how and especially why of the problem.
      If you like our efforts, we request a review
      g.page/Pepcoding/review?rc
      You can subscribe to our channel here
      ua-cam.com/users/Pepcodingabout?view_as=subscriber

    • @sachinsharma905
      @sachinsharma905 3 роки тому +2

      @@Pepcoding I have already reviewed Pepcoding in the google maps and am already subscribed.

  • @RahulGupta-wy9ej
    @RahulGupta-wy9ej 9 місяців тому

    great teacher ever seen after 12th

  • @bloody9162
    @bloody9162 2 роки тому

    The explanation for time complexity can't get better than this. Period.

    • @Pepcoding
      @Pepcoding  2 роки тому

      for better experience why don't you use this same content on nados.pepcoding.com?

  • @udaykulkarni5639
    @udaykulkarni5639 2 роки тому +1

    Wow man! This problem looked very complicated at first but as you explain it - It just kept getting easier. Every single concept taught by you is unforgettable -

  • @rajukumar-jn6yi
    @rajukumar-jn6yi Рік тому

    your teaching method is best

  • @reshihashim4094
    @reshihashim4094 2 роки тому +1

    made it way easy, thank u sir ❤️
    Love From Kashmir 😍

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

    Thanku PrabhuJi🙌🌸

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

    Amazing sir👏👏.
    The way of teaching is
    so unique and very easy way.🙏🙏

  • @S.Saurabh_
    @S.Saurabh_ Рік тому

    Here is another solution using which has less time complexity:
    int ans = 1;
    HashSet hashSet = new HashSet();
    for (int num: nums) { // nums is the array
    hashSet.add(num);
    }
    for (int val: hashSet) { //Looping through hashSet
    if (!hashSet.contains(val-1)) {
    int maxStreak = 1;
    while (hashSet.contains(val+1)) {
    maxStreak++;
    val++;
    }
    ans = Math.max(ans, maxStreak);
    }
    }
    return ans;

  • @RishiMishra1997
    @RishiMishra1997 2 роки тому

    Sir in worst case I think the third loop will not execute for exactly n times. It will execute for (2*n-1) times if there is only one consecutive sequence.
    For example [4,5,7,6,8,9,10] -> 7 times for loop will get executed for each element of array...and 6 times inner while loop will get executed for array element 4.
    Although it will not make any difference overall TC will remain O(n) but i just want to confirm that what I am thinking is correct or not.
    Sir your teaching method is very good after seeing your lectures all concepts gets crystal clear.
    ThankYou for such wonderful content.

  • @GunjanKumar-ls9ix
    @GunjanKumar-ls9ix 3 роки тому +3

    good job sir , best explanation ever.

    • @Pepcoding
      @Pepcoding  3 роки тому +3

      Glad to know that you liked the content and thank you for appreciating.
      The love and respect which I get from you people keep me highly motivated and the same I am able to forward It to you people through my videos.
      So, keep motivating, keep learning and keep loving Pepcoding😊

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

    bhai aap great ho yaaar

  • @AnkurSingh-mk9rc
    @AnkurSingh-mk9rc 3 роки тому +1

    python code if someone needs:
    class Solution:
    def longestConsecutive(self, arr: List[int]) -> int:
    d = {}
    res = []
    for i in arr:
    d[i]=True
    for i in d:
    if (i-1) in d:
    d[i] = False
    max_len = 0
    max_start = 0
    for i in d:
    if d[i] == True:
    temp_length = 1
    temp_start = i
    while ((temp_length + temp_start) in d):
    temp_length+=1
    if temp_length>max_len:
    max_start = temp_start
    max_len = temp_length
    for i in range(max_len):
    res.append(max_start+i)

    return len(res)

  • @nikhilkumarjamwal5322
    @nikhilkumarjamwal5322 2 роки тому

    Good Explanation!👌

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

    Can we solve this using union find?

  • @prasantharavindramesh1078
    @prasantharavindramesh1078 3 роки тому

    awesome explanation.Just a small clarification.The consecutive sequence can be in any order is true but what if the consecutive sequence has duplicates like for the above example say [100,1,200,1,10,4,0,3,8,2].Here the consecutive sequence is [0,1,1,2,3,4] so i need to store the frequency also correct if input has duplicates?

    • @Pepcoding
      @Pepcoding  3 роки тому

      For doubt support use nados.pepcoding.com

    • @mickyman753
      @mickyman753 2 роки тому

      if the question says to store duplicates too ,then just use the same logic for sequence , for every number in the answer seq , if it is repeating then print freq no. of times

  • @aakash1763
    @aakash1763 3 роки тому

    great bhai

  • @AnkitKumar-fj8ex
    @AnkitKumar-fj8ex 3 роки тому

    Awesome explanation sir

    • @Pepcoding
      @Pepcoding  3 роки тому

      Thanks buddy!
      Keep learning and keep growing!

  • @akanshapanchal7107
    @akanshapanchal7107 3 роки тому

    Very nice explanantion, thanks sir!

    • @Pepcoding
      @Pepcoding  3 роки тому +1

      Thankyou beta!
      I am glad you liked it. I hope that you are watching till the end and trying to understand what, how, and especially why of the problem.
      If you like our efforts, will you like to write a few words about us here (www.quora.com/What-are-the-good-websites-to-learn-data-structures-and-algorithms )

    • @akanshapanchal7107
      @akanshapanchal7107 3 роки тому +1

      @@Pepcoding sure sir!! :)

  • @mrmagician5609
    @mrmagician5609 3 роки тому +3

    Time complexity of this solution I think is: O(n*h) ; h = length of maximum consecutive sequence. Not O(n)
    Any suggestions?

    • @loserfruit9663
      @loserfruit9663 3 роки тому

      Bahar wali loop chali n baar agar each element ke liye andar wali loop n baar chalti to n*n hoti but yahan har ek element ke liye nahi totally he loop n baar chalegi that is considered as o(n),hope that makes sense

    • @creativegiant148
      @creativegiant148 3 роки тому +1

      Aesa samjh lo jo false hain vo 0 baar chalenge or jo true hain usko milla ke hamesha n hoga

    • @chantelsopio5826
      @chantelsopio5826 3 роки тому +3

      Although the time complexity appears to be quadratic due to the while loop nested within the for loop, closer inspection reveals it to be linear. Because the while loop is reached only when currentNum marks the beginning of a sequence (i.e. currentNum-1 is not present in nums), the while loop can only run for nn iterations throughout the entire runtime of the algorithm. This means that despite looking like O(n \cdot n)O(n⋅n) complexity, the nested loops actually run in O(n + n) = O(n)O(n+n)=O(n) time. All other computations occur in constant time, so the overall runtime is linear.

  • @sudoupdate
    @sudoupdate 3 роки тому +1

    // CPP AC code
    #include
    using namespace std;
    void printUsingHashMap(vector &arr){
    int n = arr.size();
    unordered_map m; // m[element] == true, so element is the starting point of the sequence
    // initialization
    for(auto e: arr){
    m[e] = true;
    }
    for(auto element : m)
    if(m.find(element.first-1)!=m.end() && m[element.first-1])
    element.second =false;

    // now all those keys which are true, are starting points of consecutive sequence
    int maxm_length=INT_MIN;
    int start;

    for(auto element: m){
    if(element.second==true){
    int length = 1;
    int i = element.first;
    while(m.find(i+1)!=m.end())
    i++,length++;

    if(length>maxm_length){
    maxm_length = length;
    start = element.first;
    }
    else if(length == maxm_length && element.first < start){
    maxm_length = length;
    start = element.first;
    }
    }
    }

    // printing the solution
    for(int i = start; i

  • @giit85
    @giit85 3 роки тому

    Great 👍❤️❤️❤️😍😍💯❣️💢

  • @umangbehl8152
    @umangbehl8152 2 роки тому

    wow explanation

    • @Pepcoding
      @Pepcoding  2 роки тому

      Glad you liked it!
      Keep learning.
      And for better experience and well organised content visit nados.pepcoding.com

  • @sukanyasinha3583
    @sukanyasinha3583 4 роки тому

    even aapne loop ke andr loop use kiya hai atleast wo element ko check krega ki next wala hai ya nhi hai to map me ksi bhi element ko search krne me hi o(log n) complexity lagti hai to n kaise hui??

    • @rahulranjan7567
      @rahulranjan7567 3 роки тому

      Map ki search O(1) hoti hai. logn hoti toh hum BST hi lete... hash banane ki jarurat hi nahi hoti

  • @rahulranjan7567
    @rahulranjan7567 3 роки тому +1

    isme duplicate element cover nahi ho payenge sir. Sari element distinct is prerequisite I assume.

    • @mohaktrivedi9591
      @mohaktrivedi9591 3 роки тому +1

      duplicate ke liye compute hoga, but it's length will be atmost = not > maxSequenceLen, thus, it won't be printed twice only computed twice. And even the computation can be ignored if at the end of first computation you make it false in hm. Dry run karo with a test case that contains duplicate start points, clear ho jayega. Mujhe bhi same doubt tha.

  • @shubhamsood1406
    @shubhamsood1406 4 роки тому

    Sir at 14:12 you said "while ne 'n' times contribute kiya". Then in for loop isn't time complexity will become n*n (n for for loop and n for while loop)?

    • @Pepcoding
      @Pepcoding  4 роки тому

      While ne over all loops n contribute kia all in all

    • @Pepcoding
      @Pepcoding  4 роки тому

      Har baar n nahi contribute kia

    • @shubhamsood1406
      @shubhamsood1406 4 роки тому +3

      @@Pepcoding Thank you sir, matlab each time n bar run hota while tabh n*n complexity hoti?

    • @creativegiant148
      @creativegiant148 3 роки тому

      @@shubhamsood1406 ha

  • @anjalisingh-sx5ct
    @anjalisingh-sx5ct 4 роки тому

    if (S.find(arr[i] - 1) == S.end())
    In c++ it's S.end( )
    Thus this S.end checks for only last element or entire set????

    • @sravanikatasani6502
      @sravanikatasani6502 3 роки тому

      it means u have checked the entire set(and not found the element), reached the end of it .

    • @sudhanshu4102
      @sudhanshu4102 3 роки тому

      S.end() actually indicates the end of the hashmap, it returns an iterator pointing to the location next to the last element of hashmap. S.find(arr[i] - 1) == S.end() this statement means you have checked the entire map and didn't find the element hence, reached the end of it .

  • @inspired_enough_to_grow_up
    @inspired_enough_to_grow_up 2 роки тому

    sir map ka creation bhi to time complexity O(n * Log n) letta hai...

    • @Pepcoding
      @Pepcoding  2 роки тому

      For better insight, visit nados.pepcoding.com, post your doubts, community will help you out there.

  • @aakashgoswami2356
    @aakashgoswami2356 3 роки тому +1

    Sir leetcode par submit karne par 69/70 tc pass ho rhe hain. Ek test case main TLE aa rha hai

    • @mritunjaykumar457
      @mritunjaykumar457 2 роки тому

      TLE aa rha hai because wo expected time se jyada time le rha hai

  • @sukanyasinha3583
    @sukanyasinha3583 4 роки тому +1

    Sir can you explain O(n) iski complexity Kaise hogi

    • @SCRIPTSAG
      @SCRIPTSAG 4 роки тому

      Basically last me jo sir ne loop lgaya hai for loop me usme while loop total n bar chelega her element ke liye kuch kuch chlega lekin total n bar chelgea bas o(n) hi ho ha

    • @sukanyasinha3583
      @sukanyasinha3583 3 роки тому

      Wo to mjhe bhi PTA hai par complexity always find in wrost case , so agar elements agar sequence me ho 1 upto n ho aur saare sequence me to so in that case toh n^2 hogi. Bcz elements to hm kuch bhi daal skte na ?? Mai is case me phuchi hu? Like Consider the case when values in a are a sequence from 1 to n... 1,2,3...n then in that case complexity will n^2

    • @SCRIPTSAG
      @SCRIPTSAG 3 роки тому

      @@sukanyasinha3583 I think sir can be clear you doubts

    • @sukanyasinha3583
      @sukanyasinha3583 3 роки тому

      @@SCRIPTSAG ji

    • @SCRIPTSAG
      @SCRIPTSAG 3 роки тому

      @@sukanyasinha3583 teligram joine Kiya hai sir ka

  • @SuperPabbs
    @SuperPabbs 4 роки тому

    Thank you

    • @Pepcoding
      @Pepcoding  4 роки тому

      You're welcome
      If you like my efforts, I request a review
      g.page/Pepcoding/review?rc
      You can subscribe to our channel here
      ua-cam.com/users/Pepcodingabout?view_as=subscriber
      For clearing your doubts, you can join our community on telegram
      t.me/pepcoding

    • @SuperPabbs
      @SuperPabbs 4 роки тому

      @@Pepcoding done. You're doing a fantastic job.

  • @sagardhankar1449
    @sagardhankar1449 3 роки тому

    Thankyou sir

  • @puskinmittal8956
    @puskinmittal8956 4 роки тому +1

    for loop ke andar while sir n kaise hua n*n hona chahiye worst case mein

    • @Pepcoding
      @Pepcoding  4 роки тому

      Worst case mei bhi n hai. Ache se sochie. For mei while hote hue bhi n hai. Total kitni baar chalega andar wala loop?

    • @anushkasharma4815
      @anushkasharma4815 4 роки тому

      Sir, not able to understand, Why it is O(n). Since the outer loop will run n times and in worst case the inner loop will also run n times, so if i am not wrong it should be O(n*n).
      Please make one video to explain it's time complexity that how it is O(n).

    • @hymnish_you
      @hymnish_you 4 роки тому +3

      @@anushkasharma4815 Outer loop runs n times but it doesn't do operations at each time...
      It just runs blindly... Which is not difficult for the compiler... Complexity is always for algorithmic operations.
      Let's say:-
      i == 1 ---> no operations
      i == 2 ---> no operations
      i == 3 ---> 3 operations
      i == 4 ---> no operations
      .
      .
      .
      i == n ---> 5 operations
      So, taking this problem into consideration... It does n operations in total

    • @crackthecode1372
      @crackthecode1372 4 роки тому +1

      @@hymnish_you u mean that if a simple for loop which is running till arr.length and not doing any operation won't have a complexity of size of array?

    • @hymnish_you
      @hymnish_you 4 роки тому

      @@crackthecode1372 yeah

  • @harshitkaushik4144
    @harshitkaushik4144 4 роки тому

    OP sir

  • @trevorPhillips284
    @trevorPhillips284 3 роки тому

    iski time complexity kaafi kharab h leetcode me submit karne pe 255 ms dikha rha h

    • @thecodingsaga
      @thecodingsaga 3 роки тому

      leetcode ke run-time par jaya karo bro! wo most optimal soln ko bhi 20% faster batata hai

  • @fashionvella730
    @fashionvella730 3 роки тому

    its not O(n)

    • @chantelsopio5826
      @chantelsopio5826 3 роки тому

      Although the time complexity appears to be quadratic due to the while loop nested within the for loop, closer inspection reveals it to be linear. Because the while loop is reached only when currentNum marks the beginning of a sequence (i.e. currentNum-1 is not present in nums), the while loop can only run for nn iterations throughout the entire runtime of the algorithm. This means that despite looking like O(n \cdot n)O(n⋅n) complexity, the nested loops actually run in O(n + n) = O(n)O(n+n)=O(n) time. All other computations occur in constant time, so the overall runtime is linear.

    • @fashionvella730
      @fashionvella730 3 роки тому

      @@chantelsopio5826 always we talk about worst case complexity and in worst case its not O(n) we dont care about best we care about worst and more worst complexity will less more our code will efficient

    • @chantelsopio5826
      @chantelsopio5826 3 роки тому +1

      @@fashionvella730 as mentioned above I am talking about worst case here. You might want to Google to better understand this logic since it's fairly well known and even on LeetCode they've explained how it's O(N) since this particular logic confuses a lot of people.

  • @purnimadwivedi6622
    @purnimadwivedi6622 2 роки тому

    hi i need ur assistance in doing the given problem kindly help me in this can i get ur official gmail id to get in touch with you for resolving my issue.

  • @divyanshuchaudhari3257
    @divyanshuchaudhari3257 3 роки тому

    Great explanation sir.

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

    thank you