Understanding complexity of stack operations

Here is the time complexity of different stack operations. For the worst case, the time complexities for stack operations are as follows:

Operation

Time Complexity

pop

O(1)

push

O(1)

top

O(1)

isEmpty

O(1)

Since the stack operates at one end that remembers the top of the stack all the time, if we want to search for an item in the stack, it means we have to search through the whole list. It is the same for accessing a particular item in the stack. Although it is not good practice to use stack for these sorts of operations, if we want to do so, we have to remember that the time complexity is based on more than general stack operations.

Operation

Time Complexity

Access

O(n)

Search

O(n)

The space complexity for stack is always O(n).

So far, we have seen how to implement stack using a PHP array and it's built-in function line array_pop and array_push. But we could have ignored the built-in functions and implemented it with manual array operations, or we could have used the array_shift and array_unshift built-in functions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset