ALGORITHM AND PYTHON REFERENCE

Glossary and library choices

Search short definitions and compare Python tools with the algorithm idea they support. These reference lookups do not change course progress.

Python library comparison

ToolUseful forBehavior and tradeoffLearn more
bisect_leftPython bisect documentation (official docs, new tab)Find the first valid insertion point in an already sorted sequence.Binary search takes O(log n) time; values equal to the target stay to the right of the returned position.Binary search
insort_leftPython bisect documentation (official docs, new tab)Insert a value into a sorted Python list while keeping it sorted.The position search is O(log n), but list insertion can move later values, so the complete operation is O(n).Binary search
collections.dequePython collections documentation (official docs, new tab)Add or remove items at both ends, such as a FIFO queue or a sliding window.Endpoint appends and pops are approximately O(1); a deque is not designed for fast access to arbitrary middle positions.Queue and deque operations
heapqPython heapq documentation (official docs, new tab)Repeatedly retrieve the smallest pending value from a priority queue.The list keeps a min-heap ordering; the smallest value is at index 0, while the remaining values are not fully sorted.Heap operations
functools.lru_cachePython functools documentation (official docs, new tab)Reuse results from repeated calls to a function with the same arguments.Stores recent function results up to a configurable limit; arguments must be hashable.Dynamic programming

Glossary

Algorithm invariant
A statement that remains true before and after each step; it helps show why an algorithm is correct. In Binary search
Lower bound
The first position whose value is not less than a target; the target may be absent. In Binary search
Upper bound
The first position whose value is greater than a target; subtracting the lower bound gives the duplicate count. In Binary search
Stable sort
A sort that preserves the original relative order of items with equal keys. In Comparison sorts
Hash collision
Two distinct keys map to the same hash-table location and need an additional resolution step. In Hash chaining
Heap invariant
Each parent has priority over its children; this exposes the next minimum or maximum without fully sorting all values. In Heap operations
Path compression
A disjoint-set optimization that makes nodes point closer to their representative during a find operation. In Union-find
Topological order
An ordering of a directed acyclic graph in which every edge points from an earlier item to a later item. In Topological order
Dynamic programming
A way to solve problems by storing results for overlapping subproblems instead of recomputing them. In Dynamic programming
Greedy choice
A locally preferred step; a correctness argument must show why choosing it still permits a globally optimal result. In Greedy methods
Backtracking
Explore a choice, continue while it can lead to a solution, and undo it when that path cannot succeed. In Backtracking
Prefix sum
A running total that can turn a range-sum query into a subtraction of two prefix values. In Prefix sums
False positive
An approximate structure reports that an item may be present even though it is absent; a false negative may be ruled out by its guarantee. In Approximate membership

Library costs

325 cost rows

FunctionTimeMemoryLesson
BloomFilter.addO(k)not statedApproximate membership structures
BloomFilter.maybe_containsO(k)not statedApproximate membership structures
PersistentStackFrame.popO(1)not statedApproximate membership structures
PersistentStackFrame.pushO(1)not statedApproximate membership structures
SkipList.containsO(log n)O(1) extra memory.Approximate membership structures
SkipList.insertO(log n)O(1) extra memory besides the new node.Approximate membership structures
backtrack_findDepends on ``combine``; worst case explores the full subset treenot statedBacktracking search
combinationsC(nnot statedBacktracking search
n_queens_countExponential in ``board_size`` in the worst case; pruning does not change the worst-case tree size in theorynot statedBacktracking search
permutationsO(n · n!)not statedBacktracking search
subsetsO(n)not statedBacktracking search
bound_vocabularyO(1)The dictionary is fixed size: O(1) time and O(1) extra memory.Input size and operation counts
classify_recurrenceO(1)A constant-size table lookup: O(1) time and O(1) extra memory.Input size and operation counts
growth_tableΘ(1)Extra memory is Θ(1) per returned row.Input size and operation counts
pair_comparison_countΘ(n²)Extra memory is Θ(1) for the indexes.Input size and operation counts
recursion_limitO(1)not statedInput size and operation counts
recursion_tree_levelsΘ(log n)Extra memory is one row per level.Input size and operation counts
UserContext.__init__O(1)Time and extra memory are both O(1).Appendix: Python tools
UserContext.requireO(1)not statedAppendix: Python tools
mainO(1)not statedAppendix: Python tools
manage_usersO(1)not statedAppendix: Python tools
modify_databaseO(1)not statedAppendix: Python tools
read_databaseO(1)not statedAppendix: Python tools
run_actionO(1)not statedAppendix: Python tools
mainO(k)not statedAppendix: Python tools
require_confirmationO(1)not statedAppendix: Python tools
show_argumentsO(k)not statedAppendix: Python tools
LinkedDeque.__contains__O(n)O(n) time, O(1) extra memory.Queue and deque operations
LinkedDeque.__init__O(1)not statedQueue and deque operations
LinkedDeque.__iter__O(n)O(n) time, O(1) extra memory.Queue and deque operations
LinkedDeque.__len__O(1)not statedQueue and deque operations
LinkedDeque.__repr__O(n)Formatting n items is O(n) time and O(n) extra memory.Queue and deque operations
LinkedDeque.append_leftO(1)not statedQueue and deque operations
LinkedDeque.append_rightO(1)not statedQueue and deque operations
LinkedDeque.insert_atO(n)not statedQueue and deque operations
LinkedDeque.pop_leftO(1)not statedQueue and deque operations
LinkedDeque.pop_rightO(1)not statedQueue and deque operations
DoublyLinkedList.__contains__O(n)O(n) time, O(1) extra memory.Doubly linked-list operations
DoublyLinkedList.__init__O(k)not statedDoubly linked-list operations
DoublyLinkedList.__iter__O(n)Only the current node is kept: O(1) extra memory.Doubly linked-list operations
DoublyLinkedList.__len__O(1)not statedDoubly linked-list operations
DoublyLinkedList.__repr__O(n)Time and extra memory are both O(n).Doubly linked-list operations
DoublyLinkedList.appendO(1)not statedDoubly linked-list operations
DoublyLinkedList.headO(1)The head is stored directly: O(1) time, no extra memory.Doubly linked-list operations
DoublyLinkedList.insert_afterO(1)not statedDoubly linked-list operations
DoublyLinkedList.move_to_frontO(1)Total O(1) time and O(1) extra memory.Doubly linked-list operations
DoublyLinkedList.pop_tailO(1)Extra memory is O(1).Doubly linked-list operations
DoublyLinkedList.prependO(1)not statedDoubly linked-list operations
DoublyLinkedList.remove_nodeO(1)not statedDoubly linked-list operations
DoublyLinkedList.reverseO(1)Only ``current`` is stored: O(1) extra memory.Doubly linked-list operations
DoublyLinkedList.tailO(1)The tail is stored directly: O(1) time, no extra memory.Doubly linked-list operations
DoublyNode.__repr__O(1)Neither neighbour is visited, so the cost does not grow with n: O(1) time and O(1) extra memory.Doubly linked-list operations
dag_dp_longest_pathO(V + E)not statedDynamic programming
edit_distanceO(nm)O(nm) time, O(min(n, m)) memory.Dynamic programming
fibonacci_moduloO(n)O(1) extra memory for the two running values.Dynamic programming
knapsack_01O(nW)O(nW) time and O(W) memory with one rolling row where n = len(weights).Dynamic programming
lis_length_patienceO(n log n)O(n log n) time from binary search on pile tops, O(n) memory.Dynamic programming
lis_length_quadraticO(n²)O(n²) time, O(n) memory.Dynamic programming
longest_common_subsequenceO(nm)O(nm) time and O(min(n, m)) memory with one row.Dynamic programming
max_non_adjacent_sumO(n)O(n) time, O(1) memory (two rolling totals).Dynamic programming
min_coin_changeO(amount × len(coins))O(amount × len(coins)) time, O(amount) memory.Dynamic programming
unbounded_knapsack_max_valueO(nW)O(nW) time, O(W) memory — same table shape as bounded coin change.Dynamic programming
word_break_possibleO(D)Building the prefix trie takes O(D) expected time and O(D) memory.Dynamic programming
Graph.__init__O(1)not statedGraph representations
Graph.add_edgeO(1)not statedGraph representations
Graph.add_vertexO(1)not statedGraph representations
Graph.neighborsO(1)not statedGraph representations
Graph.verticesO(V)not statedGraph representations
breadth_first_orderO(V + E)The queue holds at most V labels: O(V) extra memory.Graph representations
depth_first_orderO(V + E)The stack and visited set hold at most V entries: O(V) extra memory.Graph representations
dijkstra_distancesO(V^2 + E)The ``best`` map stores one integer per reachable vertex: O(V) extra memory.Graph representations
UndirectedGraph.add_edgeO(1)not statedGraph traversals
bellman_ford_distancesO(VE)O(V) extra memory.Graph traversals
bfs_distances_and_parentsO(V + E)O(V + E) time, O(V) extra memory for maps and the queue.Graph traversals
connected_componentsO(V + E)O(V + E) time, O(V) extra memory.Graph traversals
dag_shortest_pathsO(V + E)not statedGraph traversals
dijkstra_distances_heapO((V + E) log V)O(V) extra memory for the heap and the distance map.Graph traversals
floyd_warshallO(V³)O(V³) time, O(V²) memory.Graph traversals
has_directed_cycleO(V + E)not statedGraph traversals
is_bipartiteO(V + E)not statedGraph traversals
kosaraju_strongly_connected_componentsO(V + E)O(V + E) time, O(V) extra memory.Graph traversals
kruskal_minimum_spanning_weightO(E log E)not statedGraph traversals
prim_minimum_spanning_weightO((V + E) log V)not statedGraph traversals
topological_orderO(V + E)O(V + E) time and O(V) memory for indegrees and the queue.Graph traversals
zero_one_bfs_distancesO(V + E)O(V + E) time, O(V) memory.Graph traversals
fractional_knapsack_valueO(n log n)not statedGreedy methods
huffman_codesO(n log n)not statedGreedy methods
interval_scheduling_max_countO(n log n)O(n log n) sort, O(n) scan, O(1) extra memory besides output count.Greedy methods
ChainingHashTable.__delitem__O(1)not statedHash tables with chaining
ChainingHashTable.__getitem__O(1)not statedHash tables with chaining
ChainingHashTable.__init__O(bucket_count)Allocate ``bucket_count`` empty lists: O(bucket_count) time and memory.Hash tables with chaining
ChainingHashTable.__iter__O(n + b)Extra memory is O(1) besides the iterator.Hash tables with chaining
ChainingHashTable.__len__O(1)not statedHash tables with chaining
ChainingHashTable.__repr__O(n)Copying n pairs is O(n) time and O(n) extra memory.Hash tables with chaining
ChainingHashTable.__setitem__O(1)not statedHash tables with chaining
LinearProbingHashTable.__delitem__O(1)not statedHash tables with linear probing
LinearProbingHashTable.__getitem__O(1)not statedHash tables with linear probing
LinearProbingHashTable.__init__O(capacity)O(capacity) time and memory for the slot arrays.Hash tables with linear probing
LinearProbingHashTable.__iter__O(capacity)not statedHash tables with linear probing
LinearProbingHashTable.__len__O(1)not statedHash tables with linear probing
LinearProbingHashTable.__repr__O(n)Copying n pairs is O(n) time and O(n) extra memory.Hash tables with linear probing
LinearProbingHashTable.__setitem__Same probing cost as lookupnot statedHash tables with linear probing
LinearProbingHashTable.load_factorO(1)not statedHash tables with linear probing
degenerate_chain_lengthO(1)not statedHash tables with linear probing
heapifyO(n)No extra list is allocated: O(1) extra memory.Heap operations
heapsortO(n)The heap reuses the input list: O(1) extra memory besides the array being sorted.Heap operations
PriorityQueue.__contains__O(n)O(n) time, O(1) extra memory.Priority queues
PriorityQueue.__init__O(1)O(1) time and memory.Priority queues
PriorityQueue.__iter__O(n)O(n) time, O(1) extra memory.Priority queues
PriorityQueue.__len__O(1)not statedPriority queues
PriorityQueue.__repr__O(n)Formatting n items is O(n) time and O(n) extra memory.Priority queues
PriorityQueue.decrease_keyO(1)not statedPriority queues
PriorityQueue.peekO(1)not statedPriority queues
PriorityQueue.popO(log n)not statedPriority queues
PriorityQueue.pushO(log n)not statedPriority queues
bfs_layer_sizesO(V + E)The deque holds at most V labels: O(V) extra memory.Cost models and assumptions
insert_into_sortedO(n)O(1) extra memory.Cost models and assumptions
list_pop_front_cost_demoO(1)not statedCost models and assumptions
timsort_sortedO(n log n)The copy uses O(n) extra memory.Cost models and assumptions
top_k_smallestO(n log k)Building the heap is O(n log k) time and O(k) extra memory.Cost models and assumptions
vertex_cover_two_approximationO(V + E)The returned cover is O(V); ``vertices`` also creates an O(V) temporary list, so peak extra memory is O(V).Approximation guarantees
DynamicArray.__contains__O(n)O(n) time, O(1) extra memory.Dynamic-array growth
DynamicArray.__getitem__O(1)not statedDynamic-array growth
DynamicArray.__init__O(initial_capacity)Allocate one list: O(initial_capacity) time and memory.Dynamic-array growth
DynamicArray.__iter__O(n)n yields: O(n) time, O(1) extra memory.Dynamic-array growth
DynamicArray.__len__O(1)not statedDynamic-array growth
DynamicArray.__repr__O(n)Formatting n items is O(n) time and O(n) extra memory.Dynamic-array growth
DynamicArray.appendO(1)Extra memory is O(n) for n stored items.Dynamic-array growth
DynamicArray.popO(1)not statedDynamic-array growth
DynamicArray.total_copy_cost_for_appendsO(append_count)O(append_count) arithmetic steps, one per append: O(1) extra memory.Dynamic-array growth
LinkedList.__contains__O(n)O(n) time, O(1) extra memory.Singly linked list
LinkedList.__eq__O(n + m)Building the two temporary lists uses O(n + m) extra memory.Singly linked list
LinkedList.__init__O(1)not statedSingly linked list
LinkedList.__iter__O(n)The iterator holds one node reference: O(1) extra memory, plus the set inside ``iter_nodes``.Singly linked list
LinkedList.__len__O(1)not statedSingly linked list
LinkedList.__repr__O(n)Time and extra memory are both O(n).Singly linked list
LinkedList.__str__O(n)That is one pass: O(n) time and O(n) extra memory for the result.Singly linked list
LinkedList.appendO(1)No walk: O(1) time and O(1) extra memory for the new node, which is part of the list afterwards.Singly linked list
LinkedList.displayO(n)Total time O(n), extra memory O(n) for the string.Singly linked list
LinkedList.extendO(k)Extra memory is the k new nodes, which become part of the list.Singly linked list
LinkedList.insertO(n)Extra memory is the new node: O(1).Singly linked list
LinkedList.insert_sortedO(n)Extra memory is the new node: O(1).Singly linked list
LinkedList.iter_nodesO(n)The ``seen`` set stores n ids, so extra memory is O(n).Singly linked list
LinkedList.make_circularO(1)The tail is cached, so pointing it at the head is one assignment: O(1) time and O(1) extra memory.Singly linked list
LinkedList.node_atO(i)Extra memory is the one ``node`` reference: O(1).Singly linked list
LinkedList.popO(1)Extra memory is O(1).Singly linked list
LinkedList.prependO(1)That is a constant number of writes, independent of n: O(1) time and O(1) extra memory.Singly linked list
LinkedList.refreshO(n)The ``seen`` set holds n ids: O(n) extra memory.Singly linked list
LinkedList.removeO(n)Extra memory is the ``previous`` reference: O(1).Singly linked list
LinkedList.require_linearO(n)``refresh`` is O(n) time and builds a ``seen`` set of n node ids while it runs, so peak extra memory is O(n).Singly linked list
LinkedList.tailO(1)not statedSingly linked list
Node.__repr__O(1)not statedSingly linked list
add_numbersO(n + m)A few references and the carry are O(1) scratch memory.Special linked-list cases
find_cycle_startO(n)Only a few references are stored: O(1) extra memory.Fast and slow pointers
delete_without_predecessorO(1)Copying its value and skipping it is a constant number of assignments: O(1) time, O(1) extra memory.Special linked-list cases
remove_sorted_duplicatesO(n)No auxiliary collection: O(1) extra memory.Special linked-list cases
remove_unsorted_duplicatesO(n)The set stores one entry per distinct value, at most n, so extra memory is O(n).Special linked-list cases
find_intersectionO(m)``require_linear`` on each list is O(n) + O(m) time with peak O(max(n, m)) extra memory for the guards.Linked-list merge and sort
LRUCache.__init__O(1)not statedLRU cache
LRUCache.__len__O(1)not statedLRU cache
LRUCache.getO(1)Total O(1) expected time, O(1) extra memory.LRU cache
LRUCache.putO(1)Extra memory is O(1) per call.LRU cache
merge_sortedO(n + m)The result list object is O(1) extra memory.Linked-list merge and sort
merge_sorted_intoO(n + m)Extra memory is a few references: O(1).Linked-list merge and sort
end_of_first_halfO(n)Time O(n), extra memory O(1).Fast and slow pointers
middle_nodeO(n)Three references are stored: O(1) extra memory for the walk.Fast and slow pointers
modular_node_from_endO(n)``require_linear`` is O(n) time with peak O(n) extra memory for its ``seen`` set.Fast and slow pointers
modular_node_from_startO(n)One tuple is kept: O(1) extra memory beyond the iterator's ``seen`` set, which is O(n).Fast and slow pointers
nth_from_endO(L)Extra memory is the two references: O(1).Fast and slow pointers
remove_nth_from_endO(L)The anchor is one extra node: O(1) extra memory for the walk.Fast and slow pointers
group_by_position_parityO(n)Only ``odd``, ``even``, and ``even_head`` are stored: O(1) extra memory.Linked-list reversal and relinking
is_palindromeO(n)The comparison stores a few node references: O(1) extra memory.Fast and slow pointers
partitionO(1)The four head/tail references are O(1) extra memory.Linked-list reversal and relinking
RandomNode.__repr__O(1)Time O(1), extra memory O(1).Doubly linked list and the LRU cache
clone_interleavedO(n)Scratch memory is a few references: O(1), besides the n cloned nodes that form the result.Doubly linked list and the LRU cache
clone_with_mapO(n)The dictionary stores n entries: O(n) extra memory, on top of the n cloned nodes which are the output.Doubly linked list and the LRU cache
remove_cycleO(n)Extra memory is O(1) on top of whatever ``find_cycle_start`` uses, which is also O(1).Fast and slow pointers
reorderO(n)Extra memory is a handful of references: O(1).Linked-list reversal and relinking
reverse_iterativeO(1)Three references are stored: O(1) extra memory for the reversal loop.Linked-list reversal and relinking
reverse_recursiveO(n)The calls are nested n deep before any of them returns, so the call stack is O(n) extra memory.Linked-list reversal and relinking
reverse_in_blocksO(n)The anchor and a few references are O(1) extra memory.Linked-list reversal and relinking
reverse_in_pairsO(n)The anchor is one extra node: O(1) extra memory.Linked-list reversal and relinking
Reviewer.__repr__O(1)not statedSpecial linked-list cases
ReviewersList.__contains__O(n)O(n) time, O(1) extra memory.Special linked-list cases
ReviewersList.__init__O(1)Three empty references: O(1) time and O(1) extra memory.Special linked-list cases
ReviewersList.__iter__O(n)n reviewers take n steps: O(n) time, O(1) extra memory.Special linked-list cases
ReviewersList.__len__O(1)not statedSpecial linked-list cases
ReviewersList.__repr__O(n)Formatting n names is O(n) time and O(n) extra memory.Special linked-list cases
ReviewersList.add_reviewerO(1)not statedSpecial linked-list cases
ReviewersList.currentO(1)not statedSpecial linked-list cases
ReviewersList.current_nameO(1)not statedSpecial linked-list cases
ReviewersList.next_reviewerO(1)O(1) time, O(1) extra memory, regardless of how many reviewers are in the circle.Special linked-list cases
rotate_rightO(n)No new node is allocated for the values: O(1) extra memory.Linked-list reversal and relinking
sort_listO(n)The anchor and a few references are O(1) extra memory for the merge itself.Linked-list merge and sort
split_circularO(n)The second list object is O(1) extra memory; its nodes are the original ones.Special linked-list cases
PrefixSum.__init__O(n)O(n) time and memory.Two-pointer patterns
PrefixSum.range_sumO(1)not statedTwo-pointer patterns
longest_unique_substring_lengthO(n)not statedTwo-pointer patterns
sliding_window_maximumO(n)not statedTwo-pointer patterns
two_sum_sortedO(n)O(n) time, O(1) memory.Two-pointer patterns
CircularQueue.__contains__O(n)O(n) time, O(1) extra memory.Queue and deque operations
CircularQueue.__init__O(capacity)Allocate a list of ``capacity`` slots: O(capacity) time and memory.Queue and deque operations
CircularQueue.__iter__O(n)O(n) time, O(1) extra memory.Queue and deque operations
CircularQueue.__len__O(1)not statedQueue and deque operations
CircularQueue.__repr__O(n)Formatting n items is O(n) time and O(n) extra memory.Queue and deque operations
CircularQueue.dequeueO(1)not statedQueue and deque operations
CircularQueue.enqueueO(1)not statedQueue and deque operations
CircularQueue.is_emptyO(1)not statedQueue and deque operations
CircularQueue.is_fullO(1)not statedQueue and deque operations
LinkedQueue.__contains__O(n)O(n) time, O(1) extra memory.Queue and deque operations
LinkedQueue.__init__O(1)One empty doubly linked list: O(1) time and O(1) extra memory.Queue and deque operations
LinkedQueue.__iter__O(n)O(n) time, O(1) extra memory.Queue and deque operations
LinkedQueue.__len__O(1)not statedQueue and deque operations
LinkedQueue.__repr__O(n)Formatting n items is O(n) time and O(n) extra memory.Queue and deque operations
LinkedQueue.dequeueO(1)``remove_node`` on the head unlinks through ``head.next`` and ``head.prev``: O(1) time, O(1) extra memory.Queue and deque operations
LinkedQueue.enqueueO(1)not statedQueue and deque operations
LinkedQueue.is_emptyO(1)not statedQueue and deque operations
LinkedQueue.peekO(1)not statedQueue and deque operations
FenwickTree.__init__O(size)O(size) memory.Range-query structures
FenwickTree.addO(log n)not statedRange-query structures
FenwickTree.prefix_sumO(log n)not statedRange-query structures
SegmentTree.__init__O(n)not statedRange-query structures
SegmentTree.point_queryO(log n)not statedRange-query structures
SegmentTree.range_addO(log n)not statedRange-query structures
SparseTable.__init__O(n log n)O(n log n) time and memory.Range-query structures
SparseTable.range_minO(1)not statedRange-query structures
binary_searchO(log n)A few integer indexes are stored: O(1) extra memory.Binary search
binary_search_traceO(log n)O(log n) extra memory for the frame list.Binary search
lower_boundO(log n)Same halving argument as ``binary_search``: O(log n) time, O(1) extra memory.Binary search
upper_boundO(log n)Still O(log n) time and O(1) extra memory.Binary search
bubble_sortO(n²)A few index variables are the only extra memory: O(1).Comparison sorts
insertion_sortO(n²)The hole index and the key are O(1) extra memory.Comparison sorts
merge_sortO(n log n)Extra memory is O(n) for the halves, plus O(log n) for the call stack.Merge sort
quick_sortO(n log n)Extra memory is the recursion stack: expected O(log n), worst case O(n).Quicksort and partition
quick_sort_three_wayO(n)Extra memory is the recursion stack: expected O(log n), worst O(n).Quicksort and partition
binary_search_on_answerO(log(high - low))not statedBinary search on a feasible answer
comparison_sort_lower_boundO(n)not statedBinary search on a feasible answer
counting_sortO(n + maximum)Count array length ``maximum + 1``: O(maximum) extra memory.Binary search on a feasible answer
inversion_countO(n log n)O(n log n) time, O(n) extra memory for the merge buffer.Binary search on a feasible answer
lsd_radix_sortO(d · (n + base))Total O(d · (n + base)) time and O(n + base) extra memory per pass.Binary search on a feasible answer
lsd_radix_sort_stringsO(d · (n + 256))not statedBinary search on a feasible answer
quickselectO(n)O(1) extra memory besides the input list indices.Binary search on a feasible answer
selection_sortO(n²)A handful of indexes is O(1) extra memory.Comparison sorts
evaluate_infixO(n)The postfix list and the value stack are O(n) extra memory.Stack parsing and expressions
evaluate_postfixO(t)The value stack holds at most t integers: O(t) extra memory.Stack parsing and expressions
infix_to_postfixO(n)The operator stack and the output hold at most t tokens: O(n) extra memory.Stack parsing and expressions
largest_rectangleO(n)The stack holds at most n indexes plus the sentinel: O(n) extra memory.Monotonic stack patterns
MinStack.__contains__O(n)O(n) time, O(1) extra memory.Stack parsing and expressions
MinStack.__init__O(1)Two empty stacks are allocated: O(1) time and O(1) extra memory.Stack parsing and expressions
MinStack.__iter__O(n)O(n) time, O(1) extra memory.Stack parsing and expressions
MinStack.__len__O(1)not statedStack parsing and expressions
MinStack.__repr__O(n)Formatting n items is O(n) time and O(n) extra memory.Stack parsing and expressions
MinStack.minimumO(1)not statedStack parsing and expressions
MinStack.peekO(1)not statedStack parsing and expressions
MinStack.popO(1)Extra memory is O(1).Stack parsing and expressions
MinStack.pushO(1)Extra memory grows by one slot per push on the main stack and, for a non-increasing sequence, one slot per push on the minima stack as well.Stack parsing and expressions
next_greaterO(n)The The stack holds at most n indexes: O(n) extra memory.Monotonic stack patterns
sort_stackO(n²)The extra stack holds every item by the end of the first loop, so extra memory is O(n).Stack parsing and expressions
Stack.__contains__O(n)O(n) time, O(1) extra memory.Stack basics
Stack.__init__O(1)Allocating an empty list and storing ``limit`` is O(1) time and O(1) extra memory.Stack basics
Stack.__iter__O(n)O(n) time, O(1) extra memory.Stack basics
Stack.__len__O(1)not statedStack basics
Stack.__repr__O(n)Time and extra memory are O(n).Stack basics
Stack.is_emptyO(1)not statedStack basics
Stack.is_fullO(1)not statedStack basics
Stack.peekO(1)O(1) time, O(1) extra memory.Stack basics
Stack.popO(1)Extra memory is O(1).Stack basics
Stack.pushO(1)not statedStack basics
stock_spansO(n)The stack holds at most n indexes: O(n) extra memory besides the result list.Monotonic stack patterns
symbols_are_balancedO(1)The stack holds only unmatched openers, at most n of them, so extra memory is O(n) in the worst case (a string of only openers) and O(1) when brackets stay matched along the way.Stack parsing and expressions
BTree.insertO(log n)O(1) extra memory besides the new node.Storage engines and locality
BTree.searchO(log n)O(1) extra memory besides the call stack, which is O(log n).Storage engines and locality
ToyLSM.maybe_containsO(log m + r)O(1) extra memory.Storage engines and locality
ToyLSM.putO(log m)not statedStorage engines and locality
WriteAheadLog.appendO(1)O(1) extra memory for the new entry.Storage engines and locality
WriteAheadLog.replayO(n log m)O(1) extra memory besides the tree.Storage engines and locality
locality_scan_benchmarkO(repeats · n)not statedStorage engines and locality
nearest_neighbor_linearO(nd)not statedStorage engines and locality
sequential_scan_sumO(n)not statedStorage engines and locality
InvertedIndex.add_documentO(total tokens)not statedString search algorithms
InvertedIndex.queryO(length of posting list)not statedString search algorithms
Trie.__init__O(1)not statedString search algorithms
Trie.containsO(len(key))not statedString search algorithms
Trie.insertO(len(key))not statedString search algorithms
kmp_searchO(n + m)not statedString search algorithms
rabin_karp_searchO(n + m)not statedString search algorithms
run_length_encodeO(n)not statedString search algorithms
suffix_array_with_lcpO(n log² n)not statedString search algorithms
format_treeO(e)The returned string is the output, so extra memory is O(e).Appendix: Python tools
mainO(1)not statedAppendix: Python tools
BinarySearchTree.__contains__O(n)O(n) time, O(1) extra memory besides the walk.Binary search tree operations
BinarySearchTree.__init__O(1)O(1) time and O(1) extra memory.Binary search tree operations
BinarySearchTree.__iter__O(n)O(n) time, O(h) extra memory.Binary search tree operations
BinarySearchTree.__len__O(n)O(n) time, O(h) extra memory.Binary search tree operations
BinarySearchTree.__repr__O(n)Formatting n keys is O(n) time and O(n) extra memory.Binary search tree operations
BinarySearchTree.containsO(h)Same walk as ``insert`` without creating nodes: O(h) time, O(1) extra memory iteratively.Binary search tree operations
BinarySearchTree.deleteO(h)Total O(h) time, O(1) extra memory iteratively.Binary search tree operations
BinarySearchTree.inorderO(n)Each node is pushed and popped once on the stack: O(n) time, O(h) extra memory for the stack where h is the height.Binary search tree operations
BinarySearchTree.inorder_iterO(n)The stack holds at most h nodes: O(h) extra memory.Binary search tree operations
BinarySearchTree.insertO(h)h levels take h steps: O(h) time and O(1) extra memory.Binary search tree operations
LeftLeaningRedBlackTree.__contains__O(n)O(n) time, O(1) extra memory.Balanced search trees
LeftLeaningRedBlackTree.__init__O(1)not statedBalanced search trees
LeftLeaningRedBlackTree.__iter__O(n)O(n) time, O(n) extra memory for the list.Balanced search trees
LeftLeaningRedBlackTree.__len__O(1)not statedBalanced search trees
LeftLeaningRedBlackTree.__repr__O(n)Formatting n keys is O(n) time and O(n) extra memory.Balanced search trees
LeftLeaningRedBlackTree.containsO(log n)not statedBalanced search trees
LeftLeaningRedBlackTree.deleteO(log n)not statedBalanced search trees
LeftLeaningRedBlackTree.inorderO(n)O(n) time, O(n) output memory.Balanced search trees
LeftLeaningRedBlackTree.insertO(log n)Total O(log n) time, O(log n) call-stack memory recursively (O(1) if rewritten iteratively).Balanced search trees
LeftLeaningRedBlackTree.rankO(log n)not statedBalanced search trees
LeftLeaningRedBlackTree.selectO(log n)not statedBalanced search trees
inorder_iterO(n)O(n) time, O(h) extra memory.Tree traversals
level_orderO(n)The queue holds at most one frontier: O(n) extra memory in the worst case (complete last level).Tree traversals
map_inorderO(n)Same as ``BinarySearchTree.inorder_iter``: O(n) time, O(h) stack memory.Tree traversals
postorderO(n)Two passes with a stack, still O(n) time and O(h) extra memory.Tree traversals
preorderO(n)Each node is pushed and popped once on the stack: O(n) time, O(h) extra memory for height h (O(n) if the tree is a chain).Tree traversals
DisjointSet.__init__O(size)O(size) time and memory to fill parent (and rank) arrays.Union-find
DisjointSet.connectedTwo ``find`` callsnot statedUnion-find
DisjointSet.findO(n)Extra memory O(1) besides the arrays.Union-find
DisjointSet.unionO(1)not statedUnion-find
Percolation.__init__O(size²)O(size²) sites plus one virtual node: O(size²) memory.Union-find
Percolation.is_openO(1)not statedUnion-find
Percolation.openO(α(n²))O(1) extra memory per call.Union-find
Percolation.open_site_countO(1)not statedUnion-find
Percolation.percolatesO(size · α(size²))not statedUnion-find