Google Interview Solution - Find Matching Pair

Everistus Akpabio
December 01, 2018

Implementing a check in c++ based on a collection of integers and an expected sum.

The Interview

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.

Proposal

Given a collection of numbers, I need to know if the collection contains a pair, when added together, is equal to an expected sum.

Test cases
Given two collections with an expected sum of 8:
  • int set1[] = {1,2,3,9};
  • int set2[] = {1,2,4,4};
set1 should return false since no pair will equal 8 and set 2 should return true since:
set2[2] + set2[3] = 4 + 4 = 8
Thought process

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.

Solution

#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"