Solution: Find Two Numbers that Add up to "s"
This review provides a detailed analysis of the different ways to solve the previous challenge
Solution #1: Brute Force #
Press + to interact
C++
#include <iostream>#include <vector>using namespace std;vector<int> findSum(int arr[], int arrSize, int s) {vector<int> elements;for (int i = 0; i < arrSize; i++) {for (int j = i + 1; j < arrSize; j++) {if (arr[i] + arr[j] == s) {elements.push_back(arr[i]);elements.push_back(arr[j]);}}}return elements;}int main() {int arr[] = {8,4,1,6,5,9};int sum = 14;vector<int> result = findSum(arr, 6, sum);if(!result.empty())cout << "Sum of " << sum << " found: " << result[0] << " " << result[1];elsecout << "Results not found" << endl;}
This is the most time-intensive but intuitive solution. It is a lot like a modified version of a linear search.
The whole array is traversed for each element and checked for any two elements that add up to the given number s. If they are found, we print them out. To do all of the above, we use a nested for-loop and iterate over the entire array for each element
Time Complexity
Since we iterate over the entire array (size ) times, the time complexity is ...
Ask