Skip to content

Example - Analysis of an Algorithm (3-Sum Problem)

Given N distinct integers, how many triples sum to exactly zero?

30, -40, -20, -10, 40, 0, 10, 5

Answer: 4 (see below)

a[i]a[j]a[k]sum
30-40100
30-20-100
-404000
-100100

Write a program that can solve this on scale efficiently.

//Check each triple
in N = a.length;
int count = 0;
for (int i = 0; i < N; i++ ){
for (int j = i + 1; j < N; j++){
for (int k = j+1; k < N; k++){
if(a[i] + a[j] + a[k] == 0) count ++;
}
}
}
return count;

We would first take our algorithm and plot empirical data to understand our running time and how it scales. For the above code we might get a curve as such:

Ntime(s)
2500.0
5000.0
10000.1
20000.8
40006.4
800051.1
16000?
analyse
Continuing from our standard plot utilising a log-log scale we can then look at the slope to understand the efficiency of our algorithm at scale:

analyse

From our hypothesis we can now predict the running time of our program

The running time is about 1.006x 10POW(-10) x NPOW(2.999) seconds

  • 51.0 seconds for N = 8,000
  • 408.1 seconds for N = 16,000
Ntime(seconds)
8K51.1
8K51.0
8K51.1
16K410.8
Hypothesis Validated!

A quick way to estimate b in a power law relationship is by doubling our hypothesis and capturing the lg ratio.

NTimeRatiolg ratio
2500
5000.04.82.3
10000.16.92.8
20000.87.72.9
40006.48.03.0
800051.18.03.0
Here we witness a convergence of our lg ratio to a constant of 3. Exponent of N and running time.

(Determines Exponent B in Power Law && Determines constant in a power law)

  • Algorithm
  • Input Data

(Determines constant in a power law)

  • Hardware
  • Software
  • System