Pairs with given sum in an array (code/Algorithm)

แชร์
ฝัง
  • เผยแพร่เมื่อ 22 ธ.ค. 2024

ความคิดเห็น • 99

  • @VinayK22
    @VinayK22 5 ปีที่แล้ว +63

    This algorithms is only for distinct elements fails for duplicates in array

    • @mdnayab5839
      @mdnayab5839 4 ปีที่แล้ว

      correct

    • @tintiniitk
      @tintiniitk 3 ปีที่แล้ว +1

      @@mdnayab5839 The fix for duplicates needs a small improvement to this. This is especially harder when there are duplicates both on the high and the low side at the same time. To handle duplicates, instead of just storing l, r indices, you also need to store something like the indices where l last changed (let's say lAnchor) and the index where r last changed (rAnchor), and keep incrementing l and r if they are same on moving forward. Now num += (l - lAnchor) * (rAnchor - r). Now reset lAnchor = ++l and rAnchor = --r . And repeat.

    • @RahulYadav-nl1ek
      @RahulYadav-nl1ek 3 ปีที่แล้ว +2

      @@tintiniitk but it will increase the complexity
      we are already in nlogn after sorting
      if we use extra space we can do this in O(n) time and O(n) space with duplicates

    • @bikramjitdas2621
      @bikramjitdas2621 3 ปีที่แล้ว

      @@tintiniitk could you just trace an example with this approach

  • @tintiniitk
    @tintiniitk 3 ปีที่แล้ว +4

    As has been pointed out by some, this doesn't handle duplicates at all.
    The fix for duplicates needs a small improvement to this. This is especially harder when there are duplicates both on the high and the low side at the same time. To handle duplicates, instead of just storing l, r indices, you also need to store something like the indices where l last changed (let's say lAnchor) and the index where r last changed (rAnchor), and keep incrementing l and r if they are same on moving forward.
    Now if array[l] + array[r] == sum, num += (l - lAnchor) * (rAnchor - r).
    After this, reset
    lAnchor = ++l ;
    rAnchor = --r .
    And repeat.

  • @tintiniitk
    @tintiniitk 3 ปีที่แล้ว +1

    This approach is O(n.log n).
    A much better O(n) approach is using hashmaps.
    array -> hashmap . hashmap in c++ is unordered_map.
    int count = 0;
    for (auto kv: hashmap)
    {
    if (kv.first * 2 == sum)
    count += kv.second * (kv.second - 1) / 2;
    else if (kv.first < sum - kv.first)
    {
    count += hashmap[sum - kv.first];
    }
    return count;
    }

  • @ankan1994
    @ankan1994 7 ปีที่แล้ว +8

    i am promoting ur channel among my friends and they all find ur videos very helpful

  • @prateektripathi100
    @prateektripathi100 5 ปีที่แล้ว +1

    Awesome.....can't describe in words how amazing explanation it is

  • @dobbyunleashed
    @dobbyunleashed 5 ปีที่แล้ว +10

    This method does not work in case you have some numbers which are repeating multiple times in array.

    • @mdnayab5839
      @mdnayab5839 4 ปีที่แล้ว

      @Fatima faz i did not got your point. can you plz share a code snippet?

    • @TheMohit987
      @TheMohit987 2 ปีที่แล้ว

      Right

    • @TheMohit987
      @TheMohit987 2 ปีที่แล้ว

      @@mdnayab5839 This is not a full-proof solution. ❌❌❌ Like if input is:
      [2 -6 2 5 2 ]
      then right output should be [2 2], [2 2], [2 2]
      where as your code will return only two pairs.

  • @milindjain544
    @milindjain544 3 ปีที่แล้ว

    Awesome lecture too clear and crisp

  • @partapupreetham9518
    @partapupreetham9518 3 ปีที่แล้ว +10

    This algorithm fails for duplicate elements

  • @Rajveer0400
    @Rajveer0400 7 ปีที่แล้ว

    Best video ever for the array ...simple and easy concept cleared thank you so much ...

  • @Ankit13555
    @Ankit13555 7 ปีที่แล้ว +3

    also plzz discuss the O(n) as per to me...worst case will be O(nlogn)-->sorting +n for checking all nos ...is it correct?

  • @snehasisbarat2457
    @snehasisbarat2457 3 ปีที่แล้ว

    How to solve this problem if the array is unsorted and required time complexity is O(N)?

  • @preetsingh2133
    @preetsingh2133 6 ปีที่แล้ว +3

    It is failing in
    2 2 2 2 2 (sum is 4) case

  • @mcaddit6802
    @mcaddit6802 3 ปีที่แล้ว

    awesome approach sir

  • @akhileshswaroopxisrnnadbt3669
    @akhileshswaroopxisrnnadbt3669 5 ปีที่แล้ว

    @Vivekanand Khyade - Algorithm Every Day :How to solve when there are duplicate elements in array or all elements in array are same?

  • @45_ritiksharma32
    @45_ritiksharma32 4 ปีที่แล้ว +1

    Could you please explain the logic behind this code

  • @kabooby0
    @kabooby0 3 ปีที่แล้ว +1

    You can do this in O(n) time with a hashmap

  • @ankan1994
    @ankan1994 7 ปีที่แล้ว +2

    very important and frequently asked array question...thanks for uploading sirji..a similar type of question which is faced by me in interview-let we have an given array of only (1) and (-1) as elements like arr[1,-1,-1,1,1,-1.....1] so we have to count the number of sub-arrays forming the sum 0.For eg- arr[1,-1,1,-1] here no of sub arrays is 4. i know how to do it, but still i want to get it from u bcoz u always bring the best and optimal solution.

  • @bhaskarnaik5842
    @bhaskarnaik5842 3 ปีที่แล้ว

    I need explanation of this topic given a sorted and rotated array, find if there is a pair with a given sum

  • @sagar1u
    @sagar1u 5 ปีที่แล้ว

    sir this video satisfies the condition of pairs ,but if we want combination of 3 or 4(suppose a[4,1,5,6,9,0,-1,20] and sum require is 31 then it has to be return [5,6,20]) elemnets from the array then what is the code or logic

  • @devanshprakash8354
    @devanshprakash8354 3 ปีที่แล้ว

    Is this the two sum problem?

  • @sarahdaniel6862
    @sarahdaniel6862 4 ปีที่แล้ว +1

    This logic exceeds time limit on geeks for geeks.

    • @em_ashutosh
      @em_ashutosh 4 ปีที่แล้ว

      sort krtai hi game over

  • @akhileshswaroopxisrnnadbt3669
    @akhileshswaroopxisrnnadbt3669 5 ปีที่แล้ว +1

    How to solve when there are duplicate elements in array or all elements in array are same?

  • @tapanjeetroy8266
    @tapanjeetroy8266 5 ปีที่แล้ว

    Thanks for uploading it.. You are doing a great job.. Please upload more videos of competitive programming.. We really need it

  • @Prophetsarkar
    @Prophetsarkar 5 ปีที่แล้ว

    sir in the if(arr[l]+arr[r]>GS) why you put (l++) can we put (r--) there?

  • @rajeshd7389
    @rajeshd7389 7 ปีที่แล้ว +12

    Hi.... nice explanation !!!! But this algorithm has time complexity O(nlogn) or O(n2) depending upon sorting technique used .... Can you extend this approach to hashing which has time complexity O(n).

    • @Nognamogo
      @Nognamogo 6 ปีที่แล้ว +2

      I'm pretty sure the sorting algorithm is ignored here. Sorting is only worth it if you'll be running multiple algorithms on the same data. Without the sorting it's O(n) which is what the video meant.

  • @vikassrivastava6459
    @vikassrivastava6459 7 ปีที่แล้ว +1

    Hi Vivekanand - could you please upload a complete lecture on bit manipulation with some of the examples which will help in understanding the concept
    Thanks in advance

  • @suneelsai9981
    @suneelsai9981 2 ปีที่แล้ว

    6+4+1 =11 is also a pair right?

  • @Vishal-nc8ju
    @Vishal-nc8ju 5 ปีที่แล้ว

    best channel

  • @rajaindirajith1534
    @rajaindirajith1534 6 ปีที่แล้ว

    In the else case you can do l++; and r--; not or. because if the sum produce by the two number will not produce the result with any other combination

    • @abhishekat8032
      @abhishekat8032 3 ปีที่แล้ว

      what if that array has duplicate items

  • @shilpika9942
    @shilpika9942 5 ปีที่แล้ว

    sir when you find a pair and you print it then why we have to either do l++ or r-- why not both ? can u please explain?

  • @sayankundu485
    @sayankundu485 4 ปีที่แล้ว

    Suppose it says given sum = 3 ... Then how will this algorithm work

  • @surajrohankar1028
    @surajrohankar1028 5 ปีที่แล้ว

    In this example 1+2+8=11, 1+2+3+5=11 and so on, then how can we make it dynamic?

  • @vikramsingla3217
    @vikramsingla3217 5 ปีที่แล้ว

    "l++ or r--" Why to do only one of these. If we do both l++ and r--, does it make any difference? Doing both seems more correct approach to me.

  • @ihowaonaro4511
    @ihowaonaro4511 5 ปีที่แล้ว

    This is great but it doesnt consider if the array has duplicate elements. e.g if there were two 10's you would miss the sum

  • @shiva_gaming8122
    @shiva_gaming8122 2 ปีที่แล้ว

    wha if all the elements are equal

  • @naturebc
    @naturebc 2 ปีที่แล้ว

    for i = 0; i< array.length;
    for j = i+1; j

  • @amolshelke9651
    @amolshelke9651 6 ปีที่แล้ว

    can you please send here link of the code ..github ??

  • @lesnar229
    @lesnar229 3 ปีที่แล้ว

    Why need to sort arr

  • @fuadhasan0362
    @fuadhasan0362 6 ปีที่แล้ว +1

    thank you sir!! love and respect from bangladesh

  • @cricbolly3252
    @cricbolly3252 4 ปีที่แล้ว

    Great sir

  • @RajaSekhar-te5nz
    @RajaSekhar-te5nz 5 ปีที่แล้ว

    Do the program on substracting adjacent numbers in array and finally display sum of all

  • @pranaywelekar4060
    @pranaywelekar4060 3 ปีที่แล้ว

    can u send the correct code once

  • @avinashch4811
    @avinashch4811 5 ปีที่แล้ว

    Gs = 11
    I want to get [1,3,7] as output how to write code for that ?

    • @alokcom
      @alokcom 4 ปีที่แล้ว

      Thats triplet in array in array question.

  • @amolshelke9651
    @amolshelke9651 6 ปีที่แล้ว

    what if instead of finding pair of elements .. i want any number of elements whose sum is equal to given number ??

    • @varshapatil5263
      @varshapatil5263 5 ปีที่แล้ว

      I also want solution for same problem
      If you have plz share with me

  • @rahulkolte1581
    @rahulkolte1581 6 ปีที่แล้ว

    but it is giving only two elements pairs (1,2,8) this also sum is 11

  • @mohammadwahiduzzamankhan4397
    @mohammadwahiduzzamankhan4397 5 ปีที่แล้ว

    Your explanation is amazing.

  • @jermainegoss705
    @jermainegoss705 3 ปีที่แล้ว

    Can you please do quadruple sum to target? pretty please lol

  • @himanshubhatt6240
    @himanshubhatt6240 3 ปีที่แล้ว

    Thanks 😊

  • @AllTypeShorts..
    @AllTypeShorts.. 4 ปีที่แล้ว

    please explain the logic behind this code sir................

  • @mowglishihtzutoy5197
    @mowglishihtzutoy5197 4 ปีที่แล้ว

    Lot of love

  • @sukhangadsingh742
    @sukhangadsingh742 6 ปีที่แล้ว +3

    fails for {1,1,1,1}

  • @prashantverma3347
    @prashantverma3347 4 ปีที่แล้ว

    thank you

  • @seraj_valley
    @seraj_valley 4 ปีที่แล้ว +1

    no need of sorting use the concpt of hashing

  • @dineshkathania2228
    @dineshkathania2228 4 ปีที่แล้ว

    No need of sorting we can write in python in simple logic and it will cover all pair like duplicate numbers also:-
    def printPairs(arr, n, sum):
    for i in range(0, n ):
    for j in range(i + 1, n ):
    if (arr[i] + arr[j] == sum):
    print(arr[i],arr[j])

  • @aravindg6129
    @aravindg6129 3 ปีที่แล้ว

    Bro whats the complexity

  • @netturikowshikbasha4811
    @netturikowshikbasha4811 4 ปีที่แล้ว

    1 2 3 4 5 6
    the output of code is 2 but actullay 3

  • @yashchandraverma3131
    @yashchandraverma3131 4 ปีที่แล้ว

    Thanks

  • @ta3113ta
    @ta3113ta 5 ปีที่แล้ว

    Thank you sir.

  • @ankitchawla8487
    @ankitchawla8487 4 ปีที่แล้ว

    This algorithm dosen't work for duplicate elements.

  • @gamingroom6421
    @gamingroom6421 6 ปีที่แล้ว

    This method will work for only two element pairs

  • @meenakshirana7664
    @meenakshirana7664 5 ปีที่แล้ว

    Video explanation is good. But this approach of finding the count doesn't work, in case if array consists of duplicates.

    • @harderharder6713
      @harderharder6713 5 ปีที่แล้ว

      the algorithm that he has mentioned will work in case of duplicates because he is not incrementing R and decrementing L simultaneously when a pair is found ...You are talking about the case when you increase and decrease them in a single step when a pair is found..

  • @insaniyat_1512
    @insaniyat_1512 4 ปีที่แล้ว

    respect

  • @orz5516
    @orz5516 7 ปีที่แล้ว

    thank you from israel. u are great.

  • @jamesqiu6715
    @jamesqiu6715 7 ปีที่แล้ว

    What??? why need to sort the array first ? Is this the "2 sum" problem ?

  • @dileepalla6769
    @dileepalla6769 6 ปีที่แล้ว

    thanks i learn

  • @45_ritiksharma32
    @45_ritiksharma32 4 ปีที่แล้ว

    Please post more vidios

  • @swethag1146
    @swethag1146 2 ปีที่แล้ว

    Thanks for this approach. Satisfies duplicate as well. Java code below...
    int[] num = {1,2,3,4,5,6,7,8};
    Arrays.sort(num);
    int sum = 6;
    int i = 0;
    int j = num.length - 1;
    boolean found = false;

    while(i sum)
    j--;
    else if(num[i] + num[j] < sum)
    i++;
    else if(num[i] + num[j] == sum){
    System.out.println(num[i] +","+ num[j]);
    i++;
    j--;
    found = true;
    }
    }
    if(!found)
    System.out.println("pair not found");

    • @sayantaniguha8519
      @sayantaniguha8519 2 ปีที่แล้ว

      what kind of a code is this / not working

  • @tanveer.shaikh
    @tanveer.shaikh 3 ปีที่แล้ว

    Your solution is O(nlog n)

  • @TheMohit987
    @TheMohit987 2 ปีที่แล้ว

    This is not a full-proof solution. ❌❌❌ Like if input is:
    [2 -6 2 5 2 ]
    then right output should be [2 2], [2 2], [2 2]
    where as your code will return only two pairs.

  • @kirankumarmv2771
    @kirankumarmv2771 4 ปีที่แล้ว

    This algo works for duplicates aswell.. only thing is we have to have sorted array in first place.

  • @kirankumarmv2771
    @kirankumarmv2771 4 ปีที่แล้ว

    we have to do both l++ & r--, as and when we found sum.

  • @vincenr8822
    @vincenr8822 7 ปีที่แล้ว

    HELLO FRIENDS :)

  • @neerajmahapatra5239
    @neerajmahapatra5239 3 ปีที่แล้ว

    At least explain the logic behind your code just explaining code...😞

  • @backtobasics6865
    @backtobasics6865 7 ปีที่แล้ว

    not a good solution

  • @Fhhchchcddd
    @Fhhchchcddd 4 ปีที่แล้ว

    हिंदी में बोल ले भाई

  • @DeepakSingh-mw9bf
    @DeepakSingh-mw9bf 4 ปีที่แล้ว

    Waste of time🙄