Arrays and Lists Flashcards
What is an implementation of a shuffle algorithm?
This is an implementation of the Inside-Out variation of the Fisher-Yates shuffle:
To initialize an array a of n elements to a randomly shuffled copy of “source”, both 0-based
for i from 0 to n - 1 do:
j = random integer such that 0 <= j <= i
if j != i, then a[i] = a[j]
a[j] = source[i]
Time complexity of python list copy
O(n)
Time complexity of python list append[1]
O(1)
Time complexity of python list insert
O(n)
Time complexity of python list get item
O(1)
Time complexity of python list set item
O(1)
Time complexity of python list delete item
O(n)
Time complexity of python list get slice[k]
O(k)
Time complexity of python list del slice
O(n)
Time complexity of python list set slice[k]
O(k+n)
Time complexity of python list extend
O(k)
Time complexity of python list sort
O(n log n)
Time complexity of python list multiply []*k
O(nk)
Time complexity of python list x in s
O(n)
Time complexity of python list min/max
O(n)
Time complexity of python list get length
O(1)
Time complexity of python dict get item
O(1), amortized worst case O(n)
Time complexity of python dict set item
O(1), amortized worst case O(n)
Time complexity of python dict delete item
O(1), amortized worst case O(n)
what is the algorithm for rotating an array left by r?
What is the complexity of the algorithm, and what other algorithmic options are there?
The simplest possible way to rotate an array can be done with a copy. Time O(N), Space O(N), which is not that bad. def rotate_copy(s, r): N = len(s) out = [None]*N for i in range(0, len(s)): out[i] = s[(i+r)%N] return out
In-place rotation is a bit more complicated, but uses slightly less space. However, a simple inplace algorithm still requires O(N) space
We can get space down to O(1) by using the Juggling algorithm, which requires a constant temporary space. The juggling algorithm might come in handy in the case where you want to visit every item in a particular order of fixed skips, like a rotation.