3

I am trying to write a linear-time algorithm O(n), which given a table A[0..n-1] (filled with ascending natural values) checks if there is a pair A[i], A[j] which satisfies f(A[i], A[j]) = C (C is a predefined constant).

Supposing that f(a,b) = a+b the algorithm will be:

Algo Paires(A[0..N-1], C)
in: Tab A[0..n-1] and C a constant
out : Boolean
Init indice ← 0
For i ← 0..n-1 do 
    if indice ≠ i & A[indice] + A[i] = C 
      return true
    else if i = n-1 & indice ≤ n-2 
      indice++; i ← 0;
End for
return False

But if:

enter image description here

what will be the algorithm then? any suggestions ?

BlueRaja - Danny Pflughoeft
  • 84,206
  • 33
  • 197
  • 283
Mooh
  • 1,237
  • 3
  • 19
  • 38
  • 2
    It sounds like you want us to do your homework for you. – Matt Ball Mar 14 '11 at 19:16
  • 1
    I'm just looking for some help and i think that i'm in the right place... i wrote the algo myself & now i want to generalize it but unfortenaly i cant figure out how ... i dont want you do to it for me but help me with some hints or suggestions.... – Mooh Mar 14 '11 at 19:26
  • 2
    It iterates n​ times on `indice`, and in each iteration it iterates n​ times on `i`. – aaz Mar 14 '11 at 19:39
  • hmmm that's true :/ any suggestion on how to change the execution time to O(n) ? – Mooh Mar 14 '11 at 19:45
  • 1
    @aaz: Sorry, I voted up Mooh's comment, but now that I actually look at the solution, I see that you are correct; it is O(n²). @Mooh: However, it can still be done simply in O(n) *(hint: one method requires two indicies, which do not both start at 0...)* – BlueRaja - Danny Pflughoeft Mar 14 '11 at 19:47
  • The structure is roughly correct, which is why it looks like O(n), but `i` shouldn't need to be reset to 0. – aaz Mar 14 '11 at 19:57

1 Answers1

7

Hint: Suppose there is a 2D matrix whose rows and columns are sorted and you are given a number x which you need to find...