1

I have an algorithm that I think its complexity is O(n^2). However, our teacher insists that the algorithm takes O(n) time. How can it be? Here is the pseudo-code of the algorithm:

// A is the input array.
// |A| is the size of the input array.
i = 1
j = 1
m = 0
c = 0
while i < |A| {
    if A[i] == A[j] 
        c = c + 1
    j = j + 1

    if j > |A|
        if c > m
            m = c
        c = 0
        i = i + 1
        j = i
}
return m
Raphael
  • 73,212
  • 30
  • 182
  • 400
Bora
  • 119
  • 2

2 Answers2

1

If we retain only the references to i and j, the code reduces to

i = 1
j = 1
while i < |A| 
    j = j + 1
    if j > |A|
        i = i + 1
        j = i

This is equivalent to

for i in [1 |A|]
    for j in [i |A|]

... which is gone through about ${|A|^2 \over 2}$ times. So it is $\Theta(n^2)$: both $O(n^2)$ and $\Omega(n^2)$.

The algorithm appears to be looking for the maximum number of replicates in the array. There are faster ways to do so. A good hash map has (average) constant time access/update. So you can count how many of each thing are in the array in $\Theta(n)$ time. You can then find the maximum in $\Theta(n)$ time too.

So the problem admits a $\Theta(n)$ solution, but what you have been offered isn't it.

Thumbnail
  • 626
  • 3
  • 7
0

Here's the heading of your question :

Complexity of the algorithm to find occurences of a given number in a given array

Your algorithm finds multiple occurrences of all elements of the given array within itself which takes $O(n^2)$ time because $n$ elements are to be compared and each element needs $n-1$ comparisons.

But finding the multiple occurrences of a given number in an array will take only $O(n)$ time as we will have to compare only $1$ given number with $n$ elements of the given array i.e. $n$ times.

I guess you are talking about the complexity of your algorithm(which does more work than needed) but the teacher is telling you about the complexity of going through the array and comparing each number in the array with the given number.