Array Traversal Patterns in DSA Python - Time & Space Complexity
When we look at how we go through an array, we want to know how long it takes as the array gets bigger.
We ask: How does the work grow when the array size grows?
Analyze the time complexity of the following code snippet.
def print_elements(arr):
for element in arr:
print(element)
This code goes through each item in the array and prints it once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the array.
- How many times: Exactly once for each element, so as many times as the array length.
As the array gets bigger, the number of print actions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows directly with the size of the array.
Time Complexity: O(n)
This means if the array doubles in size, the time to go through it also doubles.
[X] Wrong: "Since we only have one loop, the time is constant no matter the array size."
[OK] Correct: Even one loop runs once per element, so more elements mean more work, not the same.
Understanding how simple loops grow with input size is a key skill that helps you analyze more complex code easily.
"What if we nested another loop inside to compare every element with every other? How would the time complexity change?"