Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big O for a finite, fixed size set of possible values

This question triggered some confusion and many comments about whether the algorithms proposed in the various answers are O(1) or O(n).

Let's use a simple example to illustrate the two points of view:

we want to find a long x such that a * x + b = 0, where a and b are known, non-null longs.

  • An obvious O(1) algo is x = - b / a
  • A much slower algo would consist in testing every possible long value, which would be about 2^63 times slower on average.

Is the second algorithm O(1) or O(n)?

The arguments presented in the linked questions are:

  • it is O(n) because in the worst case you need to loop over all possible long values
  • it is O(1) because its complexity is of the form c x O(1), where c = 2^64 is a constant.

Although I understand the argument to say that it is O(1), it feels counter-intuitive.

ps: I added java as the original question is in Java, but this question is language-agnostic.

like image 357
assylias Avatar asked Dec 04 '22 14:12

assylias


1 Answers

The complexity is only relevant if there is a variable N. So, the question makes no sense as is. If the question was:

A much slower algo would consist in testing every possible value in a range of N values, which would be about N times slower on average.

Is the second algorithm O(1) or O(N)?

Then the answer would be: this algorithm is O(N).

like image 137
JB Nizet Avatar answered Dec 14 '22 18:12

JB Nizet