Home > OS >  Java - find all combinations of three numbers in sorted array that have a sum smaller than a number
Java - find all combinations of three numbers in sorted array that have a sum smaller than a number

Time:07-27

The title is a mouthful so I will explain further. This is a question out of a practice test for my introduction to computer science course. Most of the questions I was able to solve by myself or find a solution online, but not for this one.

You are given a sorted array (int[] arr) of unique integers (positive and negative). You must find how many triplets (combinations of three numbers in the array) have a sum that is less than a given number (int num).

The method signature is: public static int countTriplets (int [] arr, int num)

The catch is that it must be done with the lowest possible time complexity. If I understand correctly, iterating over all the possible combinations with nested for loops would give me a time complexity of O(n^3). However, I can't think of any other solution.

I should also mention that the array should be used as an array, without using other Java classes like ArrayList.

Any help is appreciated. It doesn't have to be a complete solution in code, even just a general idea of how to solve this.

CodePudding user response:

You can try two approaches for this 3-sum smaller problem: Since the array is already sorted, you can jump right in with either algorithm.

  • Binary search approach O(n^2logn)
  • Two pointer approach : O(n^2)

I would attempt the two-pointer approach. Take a look on Leetcode for 2-sum and 3-sum problem since this is a variation of it. Best of luck!

  • Related