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

Performance analysis of 3 digits sum

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

Problem

I have a method that finds 3 numbers in an array that add up to a desired number.

public static void threeSum(int[] arr, int sum) {
    quicksort(arr, 0, arr.length - 1);
    for (int i = 0; i  j; k--) {
                if ((arr[i] + arr[j] + arr[k]) == sum) {
                    System.out.println(Integer.toString(i) + "+" + Integer.toString(j) + "+" + Integer.toString(k) + "="  + sum);
                }
            }
        }
    }
}


I'm not sure about the big O of this method. I have a hard time wrapping my head around this right now. My guess is O(n2) or O(n2logn). But these are complete guesses. I can't prove this. Could someone help me wrap my head around this?

Solution

The running time is O(n3). You have three nested loops:

  • Approximately n iterations of i



  • For each i, approximately n iterations of j



  • For each (i, j) pair, up to about n iterations of k. On average, it take just 0.5 * n iterations of k, but the constant factor doesn't matter.



Quicksort is generally O(n log n). So the total is O(n log n + 0.5 n × n × n), which is O(n3).

Since you took the trouble to sort the array, the innermost loop could be replaced by a binary search, which is O(log n). Therefore, an improved algorithm could work in O(n2 log n).

Context

StackExchange Code Review Q#46153, answer score: 7

Revisions (0)

No revisions yet.