Brute Force Method
The Two Sum issue may be solved brute-force style by using nested loops to iteratively verify every possible pair of integers in the array. However, for big datasets, this strategy is inefficient due to its O(n2) time complexity, where n is the array’s size.
Steps to implement above approach
- We use nested loop to traverse the whole array.
- The two loops will traverse through whole array.
- Find the pair if exist which will result to given sum.
Example: This example implements the above-mentioned approach.
Javascript
function twoSum(n, arr, target) { for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { if (arr[i] + arr[j] === target) return "True" ; } } return "False" ; } function main() { const n = 5; const arr = [3, 6, 4, 8, 7]; const target = 10; const ans = twoSum(n, arr, target); console.log(ans); } main(); |
Output
True
Check if Pair with given Sum Exists in Array using JavaScript
We will check if a pair with a given Sum exists in an Array or not using JavaScript.