Many interview problems that rely on stacks, queues, and hash tables, could be made easier by importing some python libraries that I rarely use. Most of these are in sections 8.3: collections, and 8.4 : heapq, in the Python documentation.
Stacks (docs)¶
First, just for reference, here is the way to implement a python stack using a list:
1 2 3 |
|
Pretty simple. Just remember that, while pop()
is a list method in python, push()
isn’t.
Priority Queue or Heap (docs)¶
There isn’t a purpose-built heap class in python. Like stacks, python heaps are implemented using a list. However, the methods for pushing, and popping and reheapifying aren’t standard list methods, so they have to be imported.
1 2 3 4 5 |
|
Queues (docs)¶
The queue must have it’s own class, because removing items from the front of a python list takes O(n) time. Each and every list element has to be moved once to the left, should the first list element be removed. I’m not certain as to why this is, since I had always thought that the underlying implementation of a python list was a linked list with indexed, random access pointers to each list element. At any rate, the deque
class, which implements the queue data structure in python, has enqueue and dequeue operations that are both O(1).
1 2 3 4 5 6 7 8 9 10 |
|
The deque
class implements a two sided queue. You enter from the left or the right. Consequentially, you can also implement a stack from the deque
class.
Dictionary or Hashtable¶
The Dictionary¶
Suppose you have a string s
. You can keep a tally of the number of letters of each kind in the word with a Python dictionary.
1 2 3 4 5 6 7 |
|
Counter Objects (docs)¶
Counters are a subclass of dictionaries, designed to keep tallies. You can pass any iterable and each element in the iterable (letters in a string, elements in a list, items in a dictionary.) Basically a Counter is a dictionary, but
1 2 3 4 5 6 7 8 |
|
Here is how you would take a tally using Counter
.
1 2 3 |
|
Default Dictionary (docs)¶
Like the Counter
objects, defaultdict
objects do not return key errors. Default dictionaries allow you to pass a lambda function as an argument that will be run whenever a value can’t be found for a given key.
1 2 |
|