Search
 
SCRIPT & CODE EXAMPLE
 

CPP

find pair with given sum in the array

#include <stdio.h>

void findPair(int nums[], int n, int target)
{
    // consider each element except the last
    for (int i = 0; i < n - 1; i++)
    {
        // start from the i'th element until the last element
        for (int j = i + 1; j < n; j++)
        {
            // if the desired sum is found, print it
            if (nums[i] + nums[j] == target)
            {
                printf("Pair found (%d, %d)
", nums[i], nums[j]);
                return;
            }
        }
    }
    // we reach here if the pair is not found
    printf("Pair not found");
}
 
int main(void)
{
    int nums[] = { 8, 7, 2, 5, 3, 1 };
    int target = 10;
 
    int n = sizeof(nums)/sizeof(nums[0]);
 
    findPair(nums, n, target);
 
    return 0;
}
Comment

find pair with given sum in the array

#include <iostream>
#include <unordered_map>
using namespace std;
 
// Function to find a pair in an array with a given sum using hashing
void findPair(int nums[], int n, int target)
{
    // create an empty map
    unordered_map<int, int> map;
 
    // do for each element
    for (int i = 0; i < n; i++)
    {
        // check if pair (nums[i], target - nums[i]) exists
 
        // if the difference is seen before, print the pair
        if (map.find(target - nums[i]) != map.end())
        {
            cout << "Pair found (" << nums[map[target - nums[i]]] << ", "
                 << nums[i] << ")
";
            return;
        }
 
        // store index of the current element in the map
        map[nums[i]] = i;
    }
 
    // we reach here if the pair is not found
    cout << "Pair not found";
}
 
int main()
{
    int nums[] = { 8, 7, 2, 5, 3, 1 };
    int target = 10;
 
    int n = sizeof(nums)/sizeof(nums[0]);
 
    findPair(nums, n, target);
 
    return 0;
}
Comment

find pair with given sum in the array

#include <iostream>
#include <algorithm>
using namespace std;
 
// Function to find a pair in an array with a given sum using sorting
void findPair(int nums[], int n, int target)
{
    // sort the array in ascending order
    sort(nums, nums + n);
 
    // maintain two indices pointing to endpoints of the array
    int low = 0;
    int high = n - 1;
 
    // reduce the search space `nums[low…high]` at each iteration of the loop
 
    // loop till the search space is exhausted
    while (low < high)
    {
        // sum found
        if (nums[low] + nums[high] == target)
        {
            cout << "Pair found (" << nums[low] << ", " << nums[high] << ")
";
            return;
        }
 
        // increment `low` index if the total is less than the desired sum;
        // decrement `high` index if the total is more than the desired sum
        (nums[low] + nums[high] < target)? low++: high--;
    }
 
    // we reach here if the pair is not found
    cout << "Pair not found";
}
 
int main()
{
    int nums[] = { 8, 7, 2, 5, 3, 1 };
    int target = 10;
 
    int n = sizeof(nums)/sizeof(nums[0]);
 
    findPair(nums, n, target);
 
    return 0;
}
Comment

Find A Pair With The Given Sum In An Array

class Main
{
    // Naive method to find a pair in an array with a given sum
    public static void findPair(int[] nums, int target)
    {
        // consider each element except the last
        for (int i = 0; i < nums.length - 1; i++)
        {
            // start from the i'th element until the last element
            for (int j = i + 1; j < nums.length; j++)
            {
                // if the desired sum is found, print it
                if (nums[i] + nums[j] == target)
                {
                    System.out.println("Pair found (" + nums[i] + "," + nums[j] + ")");
                    return;
                }
            }
        }
 
        // we reach here if the pair is not found
        System.out.println("Pair not found");
    }
 
    public static void main (String[] args)
    {
        int[] nums = { 8, 7, 2, 5, 3, 1 };
        int target = 10;
 
        findPair(nums, target);
    }
}
Comment

Counting Pairs in an Array, resulting in a given sum

<script>
/* javascript implementation of simple method to find count of
pairs with given sum*/
    var arr = [ 1, 5, 7, -1, 5 ];
 
    // Returns number of pairs in arr[0..n-1] with sum equal
    // to 'sum'
    function getPairsCount(n , sum) {
        var hm = new Map();
 
        // Store counts of all elements in map hm
        for (var i = 0; i < n; i++) {
 
            // initializing value to 0, if key not found
            if (!hm.has(arr[i]))
                hm.set(arr[i], 0);
 
            hm.set(arr[i], hm.get(arr[i]) + 1);
        }
        var twice_count = 0;
 
        // iterate through each element and increment the
        // count (Notice that every pair is counted twice)
        for (i = 0; i < n; i++) {
            if (hm.get(sum - arr[i]) != null)
                twice_count += hm.get(sum - arr[i]);
 
            // if (arr[i], arr[i]) pair satisfies the
            // condition, then we need to ensure that the
            // count is decreased by one such that the
            // (arr[i], arr[i]) pair is not considered
            if (sum - arr[i] == arr[i])
                twice_count--;
        }
 
        // return the half of twice_count
        return twice_count / 2;
    }
 
    // Driver method to test the above function
        var sum = 6;
        document.write("Count of pairs is " + getPairsCount(arr.length, sum));
 
// This code is contributed by umadevi9616
</script>
Comment

Function to find a pair in an array with a given sum using hashing

def findPair(A, sum):
 
    # create an empty dictionary
    dict = {}
 
    # do for each element
    for i, e in enumerate(A):
 
        # check if pair `(e, sum-e)` exists
 
        # if the difference is seen before, print the pair
        if sum - e in dict:
            print("Pair found at index", dict.get(sum - e), "and", i)
            return
 
        # store index of the current element in the dictionary
        dict[e] = i
 
    # No pair with the given sum exists in the list
    print("Pair not found")
Comment

Counting Pairs in an Array, resulting in a given sum

<script>
// javascript implementation of simple method to find count of
// pairs with given sum.
 
    // Returns number of pairs in arr[0..n-1] with sum equal
    // to 'sum'
    function getPairsCount(arr , n , k) {
        var m = new Map();
        var count = 0;
        for (var i = 0; i < n; i++) {
            if (m.has(k - arr[i])) {
                count += m.get(k - arr[i]);
            }
            if (m.has(arr[i])) {
                m.set(arr[i], m.get(arr[i]) + 1);
            } else {
                m.set(arr[i], 1);
            }
        }
        return count;
    }
 
    // Driver function to test the above function
        var arr = [ 1, 5, 7, -1, 5 ];
        var n = arr.length;
        var sum = 6;
        document.write("Count of pairs is " + getPairsCount(arr, n, sum));
 
// This code is contributed by umadevi9616
</script>
Comment

find a pair of elements from an array whose sum equals a given number python

#Given an array of integers and a number, write a function that finds two elements from the array whose sum is equal to the given number.
def find_pair(arr, num):
  for i in range(len(arr)):
    for j in range(i + 1, len(arr)):
      if arr[i] + arr[j] == num:
        return [arr[i], arr[j]]

print(find_pair([3, 6, 8, -8, 10, 8], 16))
[6, 10]
Comment

PREVIOUS NEXT
Code Example
Cpp :: selection sort c++ 
Cpp :: toString method in c++ using sstream 
Cpp :: C++ Calculating the Mode of a Sorted Array 
Cpp :: vector from angle 
Cpp :: c++ uint8_t header 
Cpp :: ue4 c++ replicate actor variable 
Cpp :: fill two dimensional array c++ 
Cpp :: text color c++ 
Cpp :: c++ sizeof 
Cpp :: UENUM ue4 
Cpp :: c++ delay 
Cpp :: full implementation of binary search tree in C++ 
Cpp :: find the graph is minimal spanig tree or not 
Cpp :: struct node 
Cpp :: add input in c++ 
Cpp :: C++ if...else...else if statement 
Cpp :: balanced brackets in c++ 
Cpp :: shortest path in unweighted graph bfs 
Cpp :: how to find size of int in c++ 
Cpp :: qt file explorer 
Cpp :: count c++ 
Cpp :: valid parentheses in c++ 
Cpp :: declare class c++ 
Cpp :: sort 2d vector c++ 
Cpp :: map of maps c++ 
Cpp :: qt c++ qdockwidget remove title 
Cpp :: vector insert to end 
Cpp :: subtraction of a 2d matrix in c++ 
Cpp :: point in polygon 
Cpp :: convert string to double arduino 
ADD CONTENT
Topic
Content
Source link
Name
7+7 =