-1

What i tried is in the below code.. I want to write the better way which gives the less time complexity. The below code complexity i am seeing is o(n^3).. I am looking for the sum exactly equal to target sum.. I know there is a question which is similar question but i am looking for better approach. Please suggest better approach do it using data structures

public class SumofThreeNumbers {
private String findTriplet(int[] inputArray, int targetSum) {

    for (int i = 0; i < inputArray.length; i++) {
        for (int j = i + 1; j < inputArray.length; j++) {
            for (int k = j + 1; k < inputArray.length; k++) {
                if (inputArray[i] + inputArray[j] + inputArray[k] == targetSum) {
                    return "FIRST VALUE IS===" + inputArray[i] + "\nSECOND VALUE IS===" + inputArray[j]
                            + "\nTHIRD VALUE IS===" + inputArray[k];
                }
            }

        }
    }
    return "Not FOUND";
}

public static void main(String[] args) {
    SumofThreeNumbers sumOfThreeObj = new SumofThreeNumbers();
    int[] inputArray = { 1, 2, 3, 4, 5, 6, 7, 8 };
    String result = sumOfThreeObj.findTriplet(inputArray, 20);
    System.out.println(result);
}

}

Roster
  • 1,169
  • 4
  • 12
  • 22
  • This is a special case of the "subset sum problem." Now that you know what it's called, you can probably find a solution more easily. – John Zwinck Jul 28 '18 at 08:58
  • 2
    Possible duplicate of [Finding three elements in an array whose sum is closest to a given number](https://stackoverflow.com/questions/2070359/finding-three-elements-in-an-array-whose-sum-is-closest-to-a-given-number) – user2357112 supports Monica Jul 28 '18 at 08:59

1 Answers1

0

You can find the O(n^2) solution here:

sort(S);
for i=0 to n-2 do
    a = S[i];
    start = i+1;
    end = n-1;
    while (start < end) do
        b = S[start]
        c = S[end];
        if (a+b+c == 0) then
            output a, b, c;
            // Continue search for all triplet combinations summing to zero.
        if (b == S[start + 1]) then
            start = start + 1;
        else
            end = end - 1;
        else if (a+b+c > 0) then
            end = end - 1;
        else
            start = start + 1;
    end
end
OmG
  • 15,398
  • 7
  • 42
  • 71