Count Pairs With Given Sum | Array Interview

preview_player
Показать описание
JOIN ME
—————

COMPLETE PLAYLIST
————————————

INTERVIEW PLAYLIST
————————————

QUICK SHORT VIDEOS
————————————-

Time Lines
=========
0:05 Introduction
2:19 Brute Force Solution
3:21 Best Solution

Count pairs with given sum is one of the array interview question, I have explained both the brute force and the best way to solve it.

First approach can be using two different loops and just have the comparison of all the pairs possible.Second approach or the best approach is to use an unordered_map and keep the record of occurrences.

#array #dsa #datastructure #Algorithms
Рекомендации по теме
Комментарии
Автор

I think, in unordered_map you wrongly added -1 instead of 7

MuthuKumar-vlof
Автор

#include<bits/stdc++.h>
// //[1, 7, 3, 5, 4]
// using namespace std;
// void countsum(int arr[], int n, int target)
// {
// int cnt=0;
// set<int>mp;
// for(int i=0;i<n;i++)
// {
//
// {
// cnt++;
// mp.insert(arr[i]);
// }
// else
// {
// mp.insert(arr[i]);
// }
// }
// cout<<cnt;
// }
// int main()
// {
// int n;
// cin>>n;
// int arr[n];
// for(int i=0;i<n;i++)
// {
// cin>>arr[i];
// }
// int target;
// cin>>target;
// countsum(arr, n, target);
// }

AmitKumar-tpfv
Автор

I think -1 entry will not be there . implemeted this


int main(void)
{
int sum = 6, count = 0;
vector<int> v = {1, 5, 7, 1, 1};
unordered_map<int, int> m;
for ( auto i = 0 ; i < v.size(); i++)
{
if ( m.find(sum-v[i]) == m.end() )
{
m.insert(make_pair(v[i], 1));
}
else
{
count = count + m[sum-v[i]];
m.insert(make_pair(v[i], 1));
}
}
for ( auto i : m)
cout << i.first << " "<< i.second << endl ;
cout << count ;
return 0;
}

its_dsa