Efficient implementation of Queue in python

ยท

1 min read

What is a queue?

  • Queue is a data structure that works on the principle of FIFO, First In First Out.
  • So elements/tasks/items that enter the queue first, will be executed first.
  • So, the entering priority matters a lot!
  • First come, first serve basis.
  • You can imagine a queue as a real-world example of people waiting in a queue to buy tickets for a movie!

image.png

Implementation of queue using list:

  • So considering the above use cases, a list might be a good option to implement a queue. Also a lot of times, people use a list as a queue!

    Time Complexity

  • Appending elements is O(1)
  • Poping the first/oldest element is O(n) because the entire array has to be shifted.

image.png

Better solution for implementation of queue other than a list?

  • collections.queue is the answer
  • It uses LinkedList under the hood to implement a queue!

    Time Complexity

  • Appending elements is O(1)
  • Poping the first/oldest element is O(1)

image.png

Code example:

import collections

q = collections.deque([1, 2, 3])

# append element to the q
q.append(4)

# pop the first element from the q
q.popleft()

print(q)
# o/p: deque([2, 3, 4])

=================

The End!

Linkedin github ๐Ÿš€โ˜๏ธ๐Ÿ–ค

ย