Three Number Sum
Given an integer array, return all the triplets that will sum up to the target number.
Time complexity is O(n^2). Because we are iterating through the array once with a for loop. For each of the numbers we then iterate again with a while loop. Usually, if not always, a loop within a loop leads to O(n^2) time complexity.
We are not using any extra space for this algorithm, which is great. Although, all numbers might end up being part of a triplet result, giving us a space complexity of O(n)
public List<Integer[]> calculate(int[] array,int target) { Arrays.sort(array); final List<Integer[]> triplets = new ArrayList<>(); for (var i=0;i<array.length-2;i++) { var leftIndex = i+1; var rightIndex = array.length-1; while(leftIndex < rightIndex) { var currentSum = array[i] + array[leftIndex] + array[rightIndex]; if(currentSum==target) { triplets.add(new Integer[]{array[i],array[leftIndex],array[rightIndex]}); leftIndex++; rightIndex--; } else if(currentSum < target) { leftIndex++; } else { rightIndex--; } } }
All truth passes through three stages. First, it is ridiculed. Second, it is violently opposed. Third, it is accepted as being self-evident.
Arthur Schopenhauer