Skip to content

Instantly share code, notes, and snippets.

@Brijeshpant
Last active February 17, 2020 18:40
Show Gist options
  • Save Brijeshpant/83211b3a621a0c4b83cfe002edcf5ded to your computer and use it in GitHub Desktop.
Save Brijeshpant/83211b3a621a0c4b83cfe002edcf5ded to your computer and use it in GitHub Desktop.
Find Pairs in an array

//Write a program that, given an array A[] of n numbers and another number x, determines whether or not there exist two elements in S whose sum is exactly x.

public class PairsInAnArray {
    boolean findPair(List<Integer> list, int x) {
        int count =0;
        
        //{1, 4, 45, 6, 10, -8} and sum to find be 16
        
        HashSet visited = new HashSet();
        for (int i = 0; i < list.size(); i++) {

            int toBePairedUp = x - list.get(i);
            if(visited.contains(toBePairedUp)) {
                return  true;
            }
            visited.add(list.get(i));
        }
        return false;
    }
}

And here is the test to verify

public class PairsInAnArrayTest {

    @Test
    public void findPair() {
        final PairsInAnArray pairsInAnArray = new PairsInAnArray();
        Assert.assertFalse(pairsInAnArray.findPair(Arrays.asList(1, 3, 5, 8, 4), 14));
        Assert.assertTrue(pairsInAnArray.findPair(Arrays.asList(7, 6, 5, 8, 4), 14));

    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment