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
xsuch thata * x + b = 0, whereaandbare 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), wherec = 2^64is 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.
The complexity is only relevant if there is a variable N. So, the question makes no sense as is. If the question was:
Then the answer would be: this algorithm is O(N).