I am reading this post on Big-O
It says that the following code is O(n^2):
bool ContainsDuplicates(String[] strings)
{
for(int i = 0; i < strings.Length; i++)
{
for(int j = 0; j < strings.Length; j++)
{
if(i == j) // Don't compare with self
{
continue;
}
if(strings[i] == strings[j])
{
return true;
}
}
}
return false;
}
But I can not understand why.
The inner loop does something constant.
So it is summation of 1....N of a constant. i.e. constant number O(1).
The outer loop is summation over the O(1).
So I would imagine it is n*O(1).
I think I am misunderstanding something here.
I do not think that all nested loops mean O(n^2), right?
i+1
instead of0
. As written, in the worst case (no dupes) 1/2 the comparisons are redundant.O(N)
, this code would actually beO(N^2 * M)
where M is the length of the strings.