Hackerrank Collections Deque Solution
2 min read

Hackerrank Collections Deque Solution

Hackerrank Collections Deque Solution


A deque is a double-ended queue. It can be used to add or remove elements from both ends.

Deques support thread safe, memory efficient appends and pops from either side of the deque with approximately the same  performance in either direction.

Click on the link to learn more about deque() methods.
Click on the link to learn more about various approaches to working with deques: Deque Recipes.



>>> from collections import deque
>>> d = deque()
>>> d.append(1)
>>> print d
>>> d.appendleft(2)
>>> print d
deque([2, 1])
>>> d.clear()
>>> print d
>>> d.extend('1')
>>> print d
>>> d.extendleft('234')
>>> print d
deque(['4', '3', '2', '1'])
>>> d.count('1')
>>> d.pop()
>>> print d
deque(['4', '3', '2'])
>>> d.popleft()
>>> print d
deque(['3', '2'])
>>> d.extend('7896')
>>> print d
deque(['3', '2', '7', '8', '9', '6'])
>>> d.remove('2')
>>> print d
deque(['3', '7', '8', '9', '6'])
>>> d.reverse()
>>> print d
deque(['6', '9', '8', '7', '3'])
>>> d.rotate(3)
>>> print d
deque(['8', '7', '3', '6', '9'])


Perform append, pop, popleft and appendleft methods on an empty deque .

Input Format

The first line contains an integer , the number of operations.
The next  lines contains the space separated names of methods and their values.


Output Format

Print the space separated elements of deque .

Sample Input

append 1
append 2
append 3
appendleft 4

Sample Output

1 2

Solution in Python

from collections import deque
d = deque()
actions = {
    "appendleft": d.appendleft,
    "pop": d.pop,
    "popleft": d.popleft
for i in range(int(input())):
    action = input().split()
    if len(action)>1:
        x,y = action

Enjoying these posts? Subscribe for more

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.