Data Structure Time Complexity
Contents
Data Structure Time Complexity#
Back in Lesson 16, we introduced the notion of run-time complexity and talked about this in the context of various complexities of the data structures we learned. Below, we introduce all the important operations for each data structure we learned with a short justification for why.
List#
A list is a series of values, each with an index (starting at 0, then 1, and so on).
Add:
l.append(v)takes \(\mathcal{O}(1)\) timeJust adds to the end of the
list
Contains:
v in ltakes \(\mathcal{O}(n)\) timeHas to search through whole list for
v
Get:
l[i]take \(\mathcal{O}(1)\) timeThe way
listis implemented, provided instant access to a value if you know its index. This is becauselists are a contiguous block of memory and it is easy for the computer to go to spoti
Set#
A set is a collection of unique values, no sense of “order”. All allowed operations are “magically” implemented in \(\mathcal{O}(1)\) time.
Add:
s.add(v)takes \(\mathcal{O}(1)\) timeContains:
v in stakes \(\mathcal{O}(1)\) timeGet: s
[i]not allowed
Dictionary#
Like a set , but a dict maps distinct keys to values.
Add:
d[k] = vtakes \(\mathcal{O}(1)\) timeContains:
k in dtakes \(\mathcal{O}(1)\) timeGet:
d[k]take \(\mathcal{O}(1)\) time
Understanding how set and dict magically do the contains operation in \(\mathcal{O}(1)\) time, regardless of how much data is in the structure, is very interesting and the idea we want to understand in this lecture.