This is an interview question I saw somewhere and came up with this:
import java.util.Random;
import java.util.Arrays;
class SumTwo
{
public static void main(String arg[])
{
Random r=new Random();
int arr[]=new int[5];
for(int i=0;i<arr.length;i++)
{
arr[i]=r.nextInt(20);
}
Arrays.sort(arr);
printArr(arr);
System.out.println(checkSum(arr));
}
public static boolean checkSum(int[] arr)
{
for(int i=2;i<arr.length;i++)
{
if(check(arr,0,i-1,arr[i]))
return true;
}
return false;
}
public static boolean check(int[] arr, int st, int en, int sum)
{
int add=0;
while(st<en)
{
add=arr[st]+arr[en];
if(add==sum)
return true;
else if(add>sum)
en--;
else
st++;
}
return false;
}
public static void printArr(int[] arr)
{
System.out.println("\n");
for(int i=0;i<arr.length;i++)
System.out.print(" "+arr[i]);
System.out.println("\n");
}
}
Well, yours is O(n^3). (EDIT: I misread it, you are correct, yours is O(n^2)) Like Louis Wasserman said, there’s a simple algorithm for O(n^2 log n), and here’s one for O(n^2) using a bit of extra memory:
Might need a special case for arrays containing zeros, depending on the problem definition, but the idea is there.
Intuitively, it seems there might be a clever way of doing this that’s O(n log n) or so, but I can’t immediately find any. I’ll keep thinking on it a bit more, this is a good question.