Sub topic 1
Cost Model: Counting Operations and Memory
Prerequisites
Assume that you can write basic loops and functions, use object references or pointers, and read Big-O notation. This chapter uses those ideas to compare data-structure operations.
What the cost model measures
An algorithm has two main resource costs:
- Time complexity estimates how the number of basic operations grows with input size.
- Space complexity estimates how much extra memory the algorithm needs as input size grows.
Let \(n\) be the number of stored elements. We usually count dominant operations rather than measuring seconds. A loop that examines every element performs about \(n\) operations, so its time complexity is \(O(n)\). An operation that does not depend on \(n\), such as reading an array element by index, is \(O(1)\).
Big-O describes an upper growth rate while ignoring constants and smaller terms. Thus, \(3n+7\) is \(O(n)\), and \(n^2+4n\) is \(O(n^2)\).
def count_pairs(a):
count = 0
for i in range(len(a)):
for j in range(len(a)):
count += 1
return count
print(count_pairs([10, 20, 30])) # 9The outer loop runs \(n\) times. For each outer iteration, the inner loop also runs \(n\) times. The total is \(n^2\), so the function takes \(O(n^2)\) time. The variable count uses constant extra space, so its auxiliary space is \(O(1)\).
Input space and auxiliary space
Space analysis must distinguish memory already occupied by the input from memory created by the algorithm.
If an algorithm receives an array of \(n\) elements and only uses a few variables, its auxiliary space is \(O(1)\), even though the input itself occupies \(O(n)\) memory. If it creates a second array of \(n\) elements, its auxiliary space is \(O(n)\).
Recursive calls also consume memory. A recursion depth of \(n\) creates an \(O(n)\) call stack, even when the function has no explicit collection.
Comparing common operations
The location of the target operation matters. Inserting at the beginning of an array shifts elements, while inserting after a known linked-list node only changes references.
| Structure and operation | Typical time | Reason |
|---|---|---|
| Array access by index | \(O(1)\) | Address is calculated directly |
| Array search | \(O(n)\) | Elements may be checked one by one |
| Linked-list access by position | \(O(n)\) | Nodes must be traversed |
| Linked-list insertion after known node | \(O(1)\) | A few links are redirected |
Exercise
A function scans an array once and stores every element greater than zero in a new array. What are its time and auxiliary-space complexities?
Show answer
The scan takes O(n) time. In the worst case, the new array stores n elements, so auxiliary space is O(n).