Every answer currently responding to this question tells you that the O(1)
means constant time (whatever it happens to measuring; could be runtime, number of operations, etc.). This is not accurate.
To say that runtime is O(1)
means that there is a constant c
such that the runtime is bounded above by c
, independent of the input. For example, returning the first element of an array of n
integers is O(1)
:
int firstElement(int *a, int n) {
return a[0];
}
But this function is O(1)
too:
int identity(int i) {
if(i == 0) {
sleep(60 * 60 * 24 * 365);
}
return i;
}
The runtime here is bounded above by 1 year, but most of the time the runtime is on the order of nanoseconds.
To say that runtime is O(n)
means that there is a constant c
such that the runtime is bounded above by c * n
, where n
measures the size of the input. For example, finding the number of occurrences of a particular integer in an unsorted array of n
integers by the following algorithm is O(n)
:
int count(int *a, int n, int item) {
int c = 0;
for(int i = 0; i < n; i++) {
if(a[i] == item) c++;
}
return c;
}
This is because we have to iterate through the array inspecting each element one at a time.