47. Permutations II
DFS problem. Same as 46, just to make sure at one level do not repeat duplicates.
DFS problem. Same as 46, just to make sure at one level do not repeat duplicates.
DFS practice.
Algorithm1:
Algorithms2:
It is a full permutation problem. DFS or BFS both ok.
Merge sort:
Complexity:
Analysis:
Although the problem only asks for implementing two operaions. It actually requires more than that. The two obvious and a few hidden required operations are:
First, if we want “get” to be done in O(1), hashing is a must. And we need to keep track of the “least recently used” element, hence a queue (FIFO) is considered. But if queue is used, updating the freshness of the pair will cost linear time, which is why a linklist should be used. So we can use hashing to map key to a node, where the value is saved. To update a node’s freshness from the linklist, we need to delete it from its original position, for which we need to not only know its next but also its pre — so we need to used double linklist! Finally, to delete the LRU from the hash table, we also need the key stored in the coresponding node. So now we have somthing like:
hash | key 1 | key 2 | key 3 | … |
---|---|---|---|---|
double linklist | (k1, v1) | (k2, v2) | (k3, v3) | … |
Trick: Python has a class collections.OrderedDict()
, which is a dict that keeps track of the insertion order…
Algorithm:
Analysis:
Algorithm: Insertion sort
Trick: If a node is greater than the sorted tail, make it the new tail and move on to next.
160. Intersection of Two Linked Lists
Algorithm1:
Algorithm2:
Analysis:
Both algs align the two lists by their tails.
Classic application of two pointers: slow and fast.
Algorithm: when fast catches up with slow, there is cycle.