1

i was following the this question and i felt that this can be solved in O(NLogN). Below is my algorithm:

 1. Sort list1 , list2, list3 i.e. O(NLogN)
 2. while indexA < size and indexB < size and indexC < size //here size is the array size
     int sum = a1[indexA] + a2[indexB] + a3[indexC]
     if sum < total then choose the minimum value from a1, a2, a3 and increment that index
     if sum > total print total can not be found and return
     if sum == total then print the indexes
    //this is  O(N)

Hence all total O(NLogN). Please tell me about the correctness of the above algo.

EDIT

As Muckle_ewe has explained that this algo will fail in some places so there is no point in further discussing on the algo rather please comment whether the question can be solvable in O(NLogN) if so then algo, thanks?

Community
  • 1
  • 1
Trying
  • 14,004
  • 9
  • 70
  • 110

1 Answers1

3

No that would fail on the

if sum < total then choose the minimum value from a1, a2, a3 and increment that index

line. Consider the following counter example (pseudocode)

list1 = [1, 10]
list2 = [2, 3]
list3 = [3, 4]

Let total be 7, for which the solution would be 1 + 2 + 4 (or 1 + 3 + 3). Let indexA = indexB = indexC = 0. Initial sum is then

list1[0] + list2[0] + list3[0]
1 + 2 + 3 = 6

As this is less than 7, we increase the index which gave the smallest list value, which was indexA as list1[indexA] = 1. Sum is then

list1[1] + list2[0] + list3[0]
10 + 2 + 3 = 15

As this is greater than 7 your algorithm tells us there is no solution

Muckle_ewe
  • 1,123
  • 3
  • 12
  • 18