patternMinor
When does an algorithm run in $O(1)$ time?
Viewed 0 times
timealgorithmdoeswhenrun
Problem
When can an algorithm be said to have $O(1)$ complexity? My doubt is if $n$ is specified to be a large number but constant and we cannot implement it in reality without a loop even then can we call it to have $O(1)$ time complexity? Consider the following examples.
-
Algorithm to add first 1000 natural numbers (that is I mean to say if n is specified directly). Then can we say this has $O(1)$ time complexity?
-
Finding the $7$th smallest element in a min heap. This element is present in anywhere in the first 6 levels of the heap (considering root at level 0). So to find the element we need to check $2^7 - 1$ elements. Then can we say this has $O(1)$ time complexity?
-
Algorithm to add first 1000 natural numbers (that is I mean to say if n is specified directly). Then can we say this has $O(1)$ time complexity?
-
Finding the $7$th smallest element in a min heap. This element is present in anywhere in the first 6 levels of the heap (considering root at level 0). So to find the element we need to check $2^7 - 1$ elements. Then can we say this has $O(1)$ time complexity?
Solution
If you follow the definition of $\mathcal O$, a function $f(x)\in\mathcal O(1)$ when there's an $x_0$ and $M$ such that for all $x>x_0$, $f(x) \leq M$.
For both algorithms you mention, there clearly is an upper bound on the number of steps a machine has to take to compute the result. Therefore, the time complexity for either problem will be some function $T(n)$, where $n$ is the length of the input, such that $T(n)\leq M$ for some $M$ for all $n$. Therefore $T(n)\in \mathcal O(1)$.
Note that the $\mathcal O$ notation has to do with asymptotic behavior of functions, i.e. their behavior as their input grows beyond all bounds. It doesn't care about tiny inputs, whether their length is $1$, $2^7$, or $10^{100}$.
For both algorithms you mention, there clearly is an upper bound on the number of steps a machine has to take to compute the result. Therefore, the time complexity for either problem will be some function $T(n)$, where $n$ is the length of the input, such that $T(n)\leq M$ for some $M$ for all $n$. Therefore $T(n)\in \mathcal O(1)$.
Note that the $\mathcal O$ notation has to do with asymptotic behavior of functions, i.e. their behavior as their input grows beyond all bounds. It doesn't care about tiny inputs, whether their length is $1$, $2^7$, or $10^{100}$.
Context
StackExchange Computer Science Q#18451, answer score: 2
Revisions (0)
No revisions yet.