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

Поделиться
HTML-код
  • Опубликовано: 9 окт 2024
  • Find pairs with the given sum in an array. Give the algorithm.

Комментарии • 99

  • @VinayK22
    @VinayK22 5 лет назад +63

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

    • @mdnayab5839
      @mdnayab5839 3 года назад

      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 2 года назад

      @@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

  • @dobbyunleashed
    @dobbyunleashed 5 лет назад +10

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

    • @mdnayab5839
      @mdnayab5839 3 года назад

      @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.

  • @partapupreetham9518
    @partapupreetham9518 3 года назад +10

    This algorithm fails for duplicate elements

  • @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?

  • @prateektripathi100
    @prateektripathi100 5 лет назад +1

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

  • @milindjain544
    @milindjain544 2 года назад

    Awesome lecture too clear and crisp

  • @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.

  • @Rajveer0400
    @Rajveer0400 6 лет назад

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

  • @preetsingh2133
    @preetsingh2133 5 лет назад +3

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

  • @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

  • @akhileshswaroopxisrnnadbt3669
    @akhileshswaroopxisrnnadbt3669 4 года назад

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

  • @bhaskarnaik5842
    @bhaskarnaik5842 2 года назад

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

  • @45_ritiksharma32
    @45_ritiksharma32 4 года назад +1

    Could you please explain the logic behind this code

  • @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

  • @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.

  • @kabooby0
    @kabooby0 3 года назад +1

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

  • @akhileshswaroopxisrnnadbt3669
    @akhileshswaroopxisrnnadbt3669 4 года назад +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

  • @snehasisbarat2457
    @snehasisbarat2457 3 года назад

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

  • @mcaddit6802
    @mcaddit6802 3 года назад

    awesome approach sir

  • @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.

  • @Prophetsarkar
    @Prophetsarkar 5 лет назад

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

  • @sarahdaniel6862
    @sarahdaniel6862 3 года назад +1

    This logic exceeds time limit on geeks for geeks.

  • @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

  • @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

  • @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

  • @suneelsai9981
    @suneelsai9981 2 года назад

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

  • @RajaSekhar-te5nz
    @RajaSekhar-te5nz 5 лет назад

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

  • @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?

  • @naturebc
    @naturebc Год назад

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

  • @rahulkolte1581
    @rahulkolte1581 6 лет назад

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

  • @devanshprakash8354
    @devanshprakash8354 3 года назад

    Is this the two sum problem?

  • @jermainegoss705
    @jermainegoss705 3 года назад

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

  • @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

  • @AllTypeShorts..
    @AllTypeShorts.. 3 года назад

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

  • @Vishal-nc8ju
    @Vishal-nc8ju 5 лет назад

    best channel

  • @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.

  • @netturikowshikbasha4811
    @netturikowshikbasha4811 4 года назад

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

  • @shiva_gaming8122
    @shiva_gaming8122 2 года назад

    wha if all the elements are equal

  • @ankitchawla8487
    @ankitchawla8487 4 года назад

    This algorithm dosen't work for duplicate elements.

  • @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..

  • @cricbolly3252
    @cricbolly3252 3 года назад

    Great sir

  • @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])

  • @sukhangadsingh742
    @sukhangadsingh742 6 лет назад +3

    fails for {1,1,1,1}

  • @avinashch4811
    @avinashch4811 5 лет назад

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

    • @alokcom
      @alokcom 3 года назад

      Thats triplet in array in array question.

  • @amolshelke9651
    @amolshelke9651 6 лет назад

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

  • @mohammadwahiduzzamankhan4397
    @mohammadwahiduzzamankhan4397 5 лет назад

    Your explanation is amazing.

  • @gamingroom6421
    @gamingroom6421 6 лет назад

    This method will work for only two element pairs

  • @tanveer.shaikh
    @tanveer.shaikh 3 года назад

    Your solution is O(nlog n)

  • @lesnar229
    @lesnar229 2 года назад

    Why need to sort arr

  • @fuadhasan0362
    @fuadhasan0362 6 лет назад +1

    thank you sir!! love and respect from bangladesh

  • @himanshubhatt6240
    @himanshubhatt6240 3 года назад

    Thanks 😊

  • @pranaywelekar4060
    @pranaywelekar4060 3 года назад

    can u send the correct code once

  • @yashchandraverma3131
    @yashchandraverma3131 4 года назад

    Thanks

  • @jamesqiu6715
    @jamesqiu6715 7 лет назад

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

  • @mowglishihtzutoy5197
    @mowglishihtzutoy5197 4 года назад

    Lot of love

  • @kirankumarmv2771
    @kirankumarmv2771 4 года назад

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

  • @aravindg6129
    @aravindg6129 3 года назад

    Bro whats the complexity

  • @ta3113ta
    @ta3113ta 5 лет назад

    Thank you sir.

  • @prashantverma3347
    @prashantverma3347 4 года назад

    thank you

  • @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");

  • @dileepalla6769
    @dileepalla6769 6 лет назад

    thanks i learn

  • @insaniyat_1512
    @insaniyat_1512 4 года назад

    respect

  • @kirankumarmv2771
    @kirankumarmv2771 4 года назад

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

  • @vincenr8822
    @vincenr8822 7 лет назад

    HELLO FRIENDS :)

  • @neerajmahapatra5239
    @neerajmahapatra5239 2 года назад

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

  • @orz5516
    @orz5516 7 лет назад

    thank you from israel. u are great.

  • @backtobasics6865
    @backtobasics6865 7 лет назад

    not a good solution

  • @Fhhchchcddd
    @Fhhchchcddd 4 года назад

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

  • @DeepakSingh-mw9bf
    @DeepakSingh-mw9bf 4 года назад

    Waste of time🙄