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

  Рет қаралды 61,062

Vivekanand Khyade - Algorithm Every Day

Vivekanand Khyade - Algorithm Every Day

Күн бұрын

Find pairs with the given sum in an array. Give the algorithm.

Пікірлер: 99
@VinayK22
@VinayK22 5 жыл бұрын
This algorithms is only for distinct elements fails for duplicates in array
@mdnayab5839
@mdnayab5839 4 жыл бұрын
correct
@tintiniitk
@tintiniitk 3 жыл бұрын
@@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 жыл бұрын
@@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 жыл бұрын
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 жыл бұрын
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 жыл бұрын
i am promoting ur channel among my friends and they all find ur videos very helpful
@partapupreetham9518
@partapupreetham9518 3 жыл бұрын
This algorithm fails for duplicate elements
@prateektripathi100
@prateektripathi100 5 жыл бұрын
Awesome.....can't describe in words how amazing explanation it is
@ankan1994
@ankan1994 7 жыл бұрын
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.
@Rajveer0400
@Rajveer0400 6 жыл бұрын
Best video ever for the array ...simple and easy concept cleared thank you so much ...
@naturebc
@naturebc 2 жыл бұрын
for i = 0; i< array.length; for j = i+1; j
@dobbyunleashed
@dobbyunleashed 5 жыл бұрын
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 2 жыл бұрын
Awesome lecture too clear and crisp
@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])
@preetsingh2133
@preetsingh2133 5 жыл бұрын
It is failing in 2 2 2 2 2 (sum is 4) case
@tapanjeetroy8266
@tapanjeetroy8266 5 жыл бұрын
Thanks for uploading it.. You are doing a great job.. Please upload more videos of competitive programming.. We really need it
@Ankit13555
@Ankit13555 7 жыл бұрын
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?
@kabooby0
@kabooby0 3 жыл бұрын
You can do this in O(n) time with a hashmap
@devanshprakash8354
@devanshprakash8354 3 жыл бұрын
Is this two sum problem?
@sarahdaniel6862
@sarahdaniel6862 4 жыл бұрын
This logic exceeds time limit on geeks for geeks.
@em_ashutosh
@em_ashutosh 3 жыл бұрын
sort krtai hi game over
@vikassrivastava6459
@vikassrivastava6459 7 жыл бұрын
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
@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
@netturikowshikbasha4811
@netturikowshikbasha4811 4 жыл бұрын
1 2 3 4 5 6 the output of code is 2 but actullay 3
@rajeshd7389
@rajeshd7389 7 жыл бұрын
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 жыл бұрын
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.
@mcaddit6802
@mcaddit6802 3 жыл бұрын
awesome approach sir
@snehasisbarat2457
@snehasisbarat2457 3 жыл бұрын
How to solve this problem if the array is unsorted and required time complexity is O(N)?
@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
@akhileshswaroopxisrnnadbt3669
@akhileshswaroopxisrnnadbt3669 4 жыл бұрын
How to solve when there are duplicate elements in array or all elements in array are same?
@45_ritiksharma32
@45_ritiksharma32 4 жыл бұрын
Could you please explain the logic behind this code
@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
@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?
@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
@Prophetsarkar
@Prophetsarkar 5 жыл бұрын
sir in the if(arr[l]+arr[r]>GS) why you put (l++) can we put (r--) there?
@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
@Vishal-nc8ju
@Vishal-nc8ju 5 жыл бұрын
best channel
@RajaSekhar-te5nz
@RajaSekhar-te5nz 5 жыл бұрын
Do the program on substracting adjacent numbers in array and finally display sum of all
@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?
@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.
@fuadhasan0362
@fuadhasan0362 6 жыл бұрын
thank you sir!! love and respect from bangladesh
@amolshelke9651
@amolshelke9651 6 жыл бұрын
can you please send here link of the code ..github ??
@mohammadwahiduzzamankhan4397
@mohammadwahiduzzamankhan4397 5 жыл бұрын
Your explanation is amazing.
@sayankundu485
@sayankundu485 4 жыл бұрын
Suppose it says given sum = 3 ... Then how will this algorithm work
@devanshprakash8354
@devanshprakash8354 3 жыл бұрын
Is this the two sum problem?
@seraj_valley
@seraj_valley 4 жыл бұрын
no need of sorting use the concpt of hashing
@gamingroom6421
@gamingroom6421 6 жыл бұрын
This method will work for only two element pairs
@AllTypeShorts..
@AllTypeShorts.. 4 жыл бұрын
please explain the logic behind this code sir................
@tanveer.shaikh
@tanveer.shaikh 3 жыл бұрын
Your solution is O(nlog n)
@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?
@vamsisaikrishnapaturu2261
@vamsisaikrishnapaturu2261 5 жыл бұрын
only pairs (2 numbers only)
@cricbolly3252
@cricbolly3252 4 жыл бұрын
Great sir
@rahulkolte1581
@rahulkolte1581 6 жыл бұрын
but it is giving only two elements pairs (1,2,8) this also sum is 11
@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.
@ankitchawla8487
@ankitchawla8487 4 жыл бұрын
This algorithm dosen't work for duplicate elements.
@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
@shiva_gaming8122
@shiva_gaming8122 2 жыл бұрын
wha if all the elements are equal
@suneelsai9981
@suneelsai9981 2 жыл бұрын
6+4+1 =11 is also a pair right?
@lesnar229
@lesnar229 2 жыл бұрын
Why need to sort arr
@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.
@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..
@sukhangadsingh742
@sukhangadsingh742 6 жыл бұрын
fails for {1,1,1,1}
@saikatdutta1991
@saikatdutta1991 5 жыл бұрын
how ?
@jermainegoss705
@jermainegoss705 3 жыл бұрын
Can you please do quadruple sum to target? pretty please lol
@pranaywelekar4060
@pranaywelekar4060 3 жыл бұрын
can u send the correct code once
@himanshubhatt6240
@himanshubhatt6240 3 жыл бұрын
Thanks 😊
@mowglishihtzutoy5197
@mowglishihtzutoy5197 4 жыл бұрын
Lot of love
@yashchandraverma3131
@yashchandraverma3131 4 жыл бұрын
Thanks
@prashantverma3347
@prashantverma3347 4 жыл бұрын
thank you
@ta3113ta
@ta3113ta 5 жыл бұрын
Thank you sir.
@kirankumarmv2771
@kirankumarmv2771 4 жыл бұрын
This algo works for duplicates aswell.. only thing is we have to have sorted array in first place.
@45_ritiksharma32
@45_ritiksharma32 4 жыл бұрын
Please post more vidios
@kirankumarmv2771
@kirankumarmv2771 4 жыл бұрын
we have to do both l++ & r--, as and when we found sum.
@aravindg6129
@aravindg6129 3 жыл бұрын
Bro whats the complexity
@jamesqiu6715
@jamesqiu6715 7 жыл бұрын
What??? why need to sort the array first ? Is this the "2 sum" problem ?
@dileepalla6769
@dileepalla6769 6 жыл бұрын
thanks i learn
@orz5516
@orz5516 7 жыл бұрын
thank you from israel. u are great.
@insaniyat_1512
@insaniyat_1512 4 жыл бұрын
respect
@vincenr8822
@vincenr8822 7 жыл бұрын
HELLO FRIENDS :)
@vivekanandkhyade
@vivekanandkhyade 7 жыл бұрын
Thanks Vinster..!
@arjunnatukula7128
@arjunnatukula7128 5 жыл бұрын
@@vivekanandkhyade codes plz
@backtobasics6865
@backtobasics6865 7 жыл бұрын
not a good solution
@Fhhchchcddd
@Fhhchchcddd 4 жыл бұрын
हिंदी में बोल ले भाई
@neerajmahapatra5239
@neerajmahapatra5239 3 жыл бұрын
At least explain the logic behind your code just explaining code...😞
@DeepakSingh-mw9bf
@DeepakSingh-mw9bf 4 жыл бұрын
Waste of time🙄
next greater element (use of stack)
5:37
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 58 М.
Maximum Sum SubArray (Kadane's algorithm) (Largest Sum Contigous SubArray)
17:30
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 92 М.
Quando A Diferença De Altura É Muito Grande 😲😂
00:12
Mari Maria
Рет қаралды 18 МЛН
Sigma Kid Mistake #funny #sigma
00:17
CRAZY GREAPA
Рет қаралды 14 МЛН
Beat Ronaldo, Win $1,000,000
22:45
MrBeast
Рет қаралды 78 МЛН
Segregate 0's, 1's and  2's together in an array[O(n)](Dutch National Flag Problem)
17:27
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 61 М.
Find Pairs in Array with Given Sum | Programming Tutorials
5:41
Programming Tutorials
Рет қаралды 70 М.
Leader in an Array (Code / Algorithm)
15:24
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 21 М.
Search an element in sorted and rotated array( Find PIVOT)
25:39
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 29 М.
Subarray with given sum
5:04
Techdose
Рет қаралды 203 М.
Java Two Sum Problem : Find Pair with given sum in an array
10:08
Learn With KrishnaSandeep
Рет қаралды 10 М.
Maximum Size Rectangle of All 1's Dynamic Programming
6:55
Tushar Roy - Coding Made Simple
Рет қаралды 181 М.
Quando A Diferença De Altura É Muito Grande 😲😂
00:12
Mari Maria
Рет қаралды 18 МЛН