A data structure supporting O(1) random access and worst-case O(1) append?

There is a beautiful structure called an extendible array that has worst-case O(1) insertion and O(n) memory overhead (that is, it’s asymptotically comparable to a dynamic array, but has O(1) worst-case insertion). The trick is to take the approach that the vector uses – doubling and copying – but to make the copying lazy. For … Read more

Asymptotic complexity of .NET collection classes

MSDN Lists these: Dictionary<,> List<> SortedList<,> (edit: wrong link; here’s the generic version) SortedDictionary<,> etc. For example: The SortedList(TKey, TValue) generic class is a binary search tree with O(log n) retrieval, where n is the number of elements in the dictionary. In this, it is similar to the SortedDictionary(TKey, TValue) generic class. The two classes … Read more

Maximum single-sell profit

I love this problem. It’s a classic interview question and depending on how you think about it, you’ll end up getting better and better solutions. It’s certainly possible to do this in better than O(n2) time, and I’ve listed three different ways that you can think about the problem here. Hopefully this answers your question! … Read more

Big-O of list slicing

Getting a slice is O(i_2 – i_1). This is because Python’s internal representation of a list is an array, so you can start at i_1 and iterate to i_2. For more information, see the Python Time Complexity wiki entry You can also look at the implementation in the CPython source if you want to.