Array sum of pairs

Pairs with sum problem

Given an array of integers A[N]. Find all pairs of integers in the array which sum to a given value (v)

Solution

Let us try to solve this problem using brute force approach

Code for sum of pairs method

Here is the code in Perl

This is not an efficient solution because of the nested loops. We can do better by using an efficient data structure such as a hash table. Insert all array elements into the hash table then for each element check if the difference between the given value and this array element is found in the hash table. If that is the case then print that pair and delete the difference value from the hash table to prevent printing duplicates.

Fast sum of pairs algorithm

Here is the code in Perl

If you have comments or feedback, please use the comments section below. Thanks for visiting.

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *