Sum of Three Values

Given an array of integers and a value, determine if there are any three integers in the array whose sum equals the given value.

Statement

Given an array of integers and an integer value, determine if there are any three integers in the array whose sum equals the given value. Return true if three such integers from the array are found. Otherwise, return false.

Example

Consider this array and the target sums:

g matrix Target sum 20 5 + 7 + 8 = 20 Target sum 21 No 3 values sum upto 21 array 3 7 1 2 8 4 5

Sample input

([3, 7, 1, 2, 8, 4, 5], 20)

Expected output

true

Try it yourself

#include <iostream>
#include <vector>
using namespace std;
bool FindSumOfThree(vector<int> nums, int required_sum) {
// TODO: Write - Your - Code
return false;
}

Solution 1

The simple and naive solution is to have three nested loops iterate over all unordered triples to see if their sum is equal to the given integer or not. Although this works, it’s not efficient.

There exist other solutions with much better time complexities. We’ll look at them later in this lesson.

#include <iostream>
#include <vector>
using namespace std;
bool FindSumOfThree(vector<int> nums, int required_sum) {
// A variable to store the sum of the current elements
int sum = 0;
for (int i = 0; i < nums.size() - 2; ++i) {
for (int j = i + 1; j < nums.size() - 1; ++j) {
for (int k = j + 1; k < nums.size(); ++k) {
// i, j and k are indices to cater the scenario in
// which same array element is used to calculate the sum.
if ((i != j) && (j != k) && (k != i)) {
sum = nums[i] + nums[j] + nums[k];
if (sum == required_sum) {
return true;
}
}
}
}
}
return false;
}
int main() {
vector<int> nums_1 = {3, 7, 1, 2, 8, 4, 5};
vector<int> test_list_1 = {10, 20, 21};
cout << "1. Original array: ";
// A custom PrintList function to print the vector
PrintList(nums_1);
for (int test : test_list_1) {
if (FindSumOfThree(nums_1, test)) {
cout << " Sum for " << test << " exists " << endl;
} else {
cout << " Sum for " << test << " does not exist " << endl;
}
}
cout << "--------------------------------------------------------------------"
"----------------------------------\n"
<< endl;
vector<int> nums_2 = {-1, 2, 1, -4, 5, -3};
vector<int> test_list_2 = {-8, 0, 7};
cout << "2. Original array: ";
// A custom PrintList function to print the vector
PrintList(nums_2);
for (int test : test_list_2) {
if (FindSumOfThree(nums_2, test)) {
cout << " Sum for " << test << " exists " << endl;
} else {
cout << " Sum for " << test << " does not exist " << endl;
}
}
cout << "------------------------------------------------------------------------------------------------------\n"<< endl;
}

Time complexity

The time complexity of this solution is cubic, O(n3)O(n^3) ...

Access this course and 1400+ top-rated courses and projects.