Data Structures & Algorithms in Swift: Part 2— Queue

Samarth Paboowal
The Startup
Published in
4 min readApr 15, 2020

--

Photo by Levi Jones on Unsplash

What is Queue?

Queue is a linear data structure which follows a particular order in terms of which operations are performed (FIFO — First in first out). It is named as queue because it behaves like any real world queue that you may encounter. For example a queue of humans waiting outside a store. If you consider that queue humans can enter a queue at the end and anyone can leave the queue from the front.

Operations on Queue

We will use an array for internal storage of the Queue as it gives us easy methods for adding & removing elements.

ENQUEUE

Enqueuing means to add an element at end of the queue. It simply means we will add an element to the end of array which is a constant time operation. So time complexity for Enqueuing will be O(1) in most cases. But in some cases if the array is full while enqueuing an element Swift will create a new array of double size and move all the elements to the new array, this will be a linear time operation O(n).

DEQUEUE

Dequeuing means to remove an element from the front of the queue. It simply means we will remove an element from the front of the array. Removal of first element is a 2 step process, in first step the element will be…

--

--