Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over array of integers to find a sequence based on an O(N) solution?

I saw following question and tried to find an answer for that.

Question:  Given a sequence of positive integers A and an integer T, return whether there is a *continuous sequence* of A that sums up to exactly T
Example
[23, 5, 4, 7, 2, 11], 20. Return True because 7 + 2 + 11 = 20 
[1, 3, 5, 23, 2], 8. Return True  because 3 + 5 = 8
[1, 3, 5, 23, 2], 7 Return False because no sequence in this array adds up to 7

Note: We are looking for an O(N) solution. There is an obvious O(N^2) solution which is a good starting point but is not the final solution we are looking for.

My answer to above question is:

public class Tester {
    public static void main(String[] args) {
        int[] myArray = {23, 5, 4, 7, 2, 11};
        System.out.println(isValid(myArray, 20));
    }

    public static boolean isValid(int[] array, int sum) {
        int pointer = 0;
        int temp = 0;

        while (pointer < array.length)
        {
            for (int i = pointer; i < array.length; i++)
            {
                if (array[i] > sum)
                    break;

                temp += array[i];
                if (temp == sum)
                    return true;
                else if (temp > sum)
                    break;
                // otherwise continue
            }

            temp = 0;
            pointer++;
        }

        return false;
    }
}

I think my answer is O(N^2) which is not acceptable based on Question. Is there a solution based on O(N)?

like image 877
Hesam Avatar asked Aug 07 '15 07:08

Hesam


1 Answers

You only need to loop once actually which is O(N).

Start adding from index 0 and once you exceed the sum start removing from the beginning of the array. if temp falls below sum continue looping.

  public static boolean isValid(int[] array, int sum) {
    int init = 0,temp = 0;

    for (int i = 0; i < array.length; i++) {
      temp += array[i];
      while (temp > sum) {
        temp -= array[init];
        init++;
      }
      if (temp == sum)
        return true;
    }
    return false;
  }
like image 60
dogant Avatar answered Sep 28 '22 01:09

dogant