HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Two sum algorithm variant

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
algorithmtwovariantsum

Problem

I need to compute the number of target values \$t\$ in the range: \$-10000 \le t \le 10000\$ (inclusive) such that there are distinct numbers \$x, y\$ in the input file that satisfy \$t= x+y\$. I have the code which does work and would like to optimize it to run it faster.

Also, we'll count the sum \$t\$ only once. If there are two \$x,y\$ pairs that add to 55, you will only increment the result once.

public static int Calculate(int start, int finish, HashSet numbers)
{
    int result = 0;
    for (int sum = start; sum <= finish; sum++)
    {
        foreach (long n in numbers)
        {
            if (numbers.Contains(sum - n) && n != (sum - n))
            {
                result++;
                break;
            }
        }
    }

    return result;
}


This is an assignment and I completed it with full marks. My code is taking like 30 minutes to run against the data set of 1 million numbers. I tried to think a way to optimize my code, but couldn't get to the right thought and would appreciate some help.

Solution

There is no need to iterate over the range. Consider a pseudocode:

sort numbers from the input file into an array A
N = size of collection
result = 0
for i in [0..N)
    find largest j (j > i) such that A[i] + A[j]  i) such that A[i] + A[k] > finish
    result += k - j


Each find is \$O(\log N)\$ at worst. Overall complexity is \$O(N \log N)\$ regardless of the target range.

Code Snippets

sort numbers from the input file into an array A
N = size of collection
result = 0
for i in [0..N)
    find largest j (j > i) such that A[i] + A[j] < start
    find smallest k (k > i) such that A[i] + A[k] > finish
    result += k - j

Context

StackExchange Code Review Q#101417, answer score: 6

Revisions (0)

No revisions yet.