The fastest algorithm to find the largest span (i,j) such that , ai + ai+1 +…+aj = bi + bi+1 +…+bj in arrays a and b

StackOverflow https://stackoverflow.com/questions/7994101

Question

I encountered this problem while preparing for my exams.

Given two arrays of numbers a1,..., an and b1,....,bn where each number is 0 or 1, the fastest algorithm to find the largest span (i,j) such that , ai + ai+1 +....+aj = bi + bi+1 +....+bj or report that there is not such span.

(A) Takes O(3^n) and omega(2^n) time if hashing is permitted.

(B) Takes O(n^3) and omega(n^2.5) and time in the key comparison mode

(C)Takes theta(n) time and space

(D)Takes O(square-root(n)) time only if the sum of 2n elements is an even number.

Was it helpful?

Solution

The only solution I can think of has O(n^2) and omega(n) time if anybody bothers to do the right check. It could probably be improved if anybody manages to find a way to take advantage of all values being 0 and 1.

int[] a = { 1, 1, 0, 1, 1, 0, 1, 0, 1 };
int[] b = { 0, 1, 0, 0, 1, 1, 0, 1, 0 };

int lastSum = 0; int lastI = 0; int lastJ = 0;
int sumA = 0; int sumB = 0; 
for(int i = 0; i < a.Length; i++) // start the sum at [i].
{
    sumA = a[i]; sumB = b[i];
    for (int j = i + 1; j < a.Length; j++) // summing ends on [j]
    //do
    {
        if (sumA == sumB && (lastJ - lastI < j - i))
        {
            lastSum = sumA;
            lastI = i; lastJ = j;
            if (j == a.Length - 1) // you will never find a bigger interval.
            {
                Console.Out.WriteLine("(i, j) = (" + lastI + ", " + lastJ + ")");
                return;
            }
        }
        sumA += a[j];
        sumB += b[j];
    }
}
Console.Out.WriteLine("(i, j) = (" + lastI + ", " + lastJ + ")");

OTHER TIPS

Here is an O(n) algorithm,

l=[1,1,1,1,0,1,0,1,1,0,1,0,0,0,1,1,1,1,0]
m=[0,0,0,0,1,0,1,1,1,0,0,0,1,1,1,0,0,0,1]
delta=[]
for i in range(0,len(l)):
    delta.append(l[i]-m[i])

leftsum=[0]
for i in range(1,len(l)+1):
    leftsum.append(leftsum[i-1]+delta[i-1])

sumHash=[-1]*len(l)

maxLen=0;
leftIndex=-1
rightIndex=-1

for i in range(0,len(l)+1):
    if sumHash[leftsum[i]]!=-1:
        if maxLen<i-sumHash[leftsum[i]]:
            maxLen=i-sumHash[leftsum[i]]
            leftIndex=sumHash[leftsum[i]]
            rightIndex=i-1
    else:
        sumHash[leftsum[i]]=i

print 'len=',maxLen,'left=',leftIndex,'right=',rightIndex
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top