The interview question I will be solving is from the google example coding interview below. Within the first 8 minutes they discuss what the function should solve.
Given a collection of numbers, I need to know if the collection contains a pair, when added together, is equal to an expected sum.
- int set1[] = {1,2,3,9};
- int set2[] = {1,2,4,4};
Being put on the spot during an interview, thinking straight might be a bit challenging. But as the interviewer suggested; testing sum of the pairs is a quick and simple way of solving this.
In this example, I will also be using c++ for the algorithm, use 2 for-loops for cycling through the indexes and checking its sum with the other elements. Our function FindPair will take three parameters, the array, the array size and the sum we’re looking for.
#include "iostream"
using namespace std;
bool FindPair(int set[], int size, int sum);
int main() {
int set1[] = {1, 2, 3, 9};
int set2[] = {1, 2, 4, 4};
int size = sizeof(set2) / sizeof(*set2);
if(FindPair(set2, size, 8))
cout << "Matching pair found";
else cout << "No pair found";
return 0;
}
bool FindPair(int set[], int size, int sum) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (j != i) {
if (set[i] + set[j] == sum)
return true;
}
}
}
return false;
}
This code should print "Matching pair found"