[Algorithms] – The sum of pairs

Problem :

Given a set of numbers, you need check if has two numbers in this set that the sum is igual an integer number.

If there is you should return 1, otherwise 0.

Inputs :

– N integer corresponding to the sum;
– N integer corresponding to the number of array elements;
– 0..n – set elements;

My solution :

private static final Integer FOUND = 1;
private static final Integer NOT_FOUND = 0;

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    List<Integer> array = new ArrayList<>();
    Integer number = scan.nextInt();
    Integer counter = scan.nextInt();
    int i = 0;
    while( i < counter ) {
    Integer output1 = hasParNumberEqualsSun(number, array);

private static int hasParNumberEqualsSun(Integer number, List<Integer> inputArray) {
    Integer result = NOT_FOUND;
    for (int i=0; i < inputArray.size(); i++){
        for (int x=1; x < inputArray.size(); x++){
            if (isSunEqualsN(number, inputArray.get(i), inputArray.get(x))) {
                result = FOUND;
        if ( result == FOUND) break;
    return result;

private static boolean isSunEqualsN(Integer number, Integer firstNumber, Integer secondNumber) {
    if ( number.equals(firstNumber+secondNumber) ){
        return true;
    return false;


  1. I hadn’t realised that it was an old article.
    But checking for a sum that’s twice the value of the last element always returns FOUND e.g. number:20, list: 1,2,3,10 returns found.
    also, the inner loop scans the whole list unnecessarily, changing the following:
    for (int i=0; i < inputArray.size(); i++){
    for (int x=1; x < inputArray.size(); x++){
    for (int i=0; i < (inputArray.size()-1); i++){
    for (int x=i+1; x < inputArray.size(); x++){
    would fix both issues (bug and speed improvement)

    Liked by 1 person

    1. Yep. It is old, however, I remember that it passed in many test cases and in some performance tests either. However, shows that you could find a bug and how to improve the speed. Really tks for the collab: -)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s