Given the classical problem to find triplets that sum to zero in an array. Is my Scala implementation correct and executed in O(N^2)? If yes, why? Can someone make a running time analysis.
What other ways could we solve this issue? With duplicated elements and not using the two pointer technique?
def tripletsFromArrayThatSumZero(input: Array[Int]): Array[Array[Int]] = {
val target = 0 // the target is the number after the sum
val sortedArray = input.sorted
var resultsArrayOfTriplets = Array[Array[Int]]()
for (i <- sortedArray.indices) {
var j = i + 1
var k = sortedArray.length - 1
val twoSum = target - sortedArray(i)
Breaks.breakable {
while (j < sortedArray.length) {
val sum = sortedArray(j) + sortedArray(k)
if (k == j) Breaks.break()
if (sum > twoSum) {
k -= 1
} else if (sum < twoSum) {
j += 1
} else if (sum == twoSum) {
val triplet = Array(sortedArray(i), sortedArray(j), sortedArray(k) )
resultsArrayOfTriplets = resultsArrayOfTriplets :+ triplet
Breaks.break()
}
}
}
}
resultsArrayOfTriplets
}