2D array indexing (row, col) in NumPy - Time & Space Complexity
We want to understand how long it takes to get a value from a 2D array using row and column indexes.
How does the time needed change when the array gets bigger?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.random.rand(1000, 1000) # Create a 2D array with 1000 rows and 1000 columns
value = arr[500, 700] # Access the element at row 500, column 700
This code creates a large 2D array and accesses one element by specifying its row and column.
- Primary operation: Accessing a single element by its row and column index.
- How many times: Exactly once for this access.
Getting one element from a 2D array takes the same time no matter how big the array is.
| Input Size (n x n) | Approx. Operations |
|---|---|
| 10 x 10 | 1 |
| 100 x 100 | 1 |
| 1000 x 1000 | 1 |
Pattern observation: The time to access one element stays the same even if the array grows larger.
Time Complexity: O(1)
This means accessing an element by row and column is done in constant time, no matter the array size.
[X] Wrong: "Accessing an element in a big 2D array takes longer because the array is large."
[OK] Correct: The computer calculates the element's position directly using the indexes, so it does not need to look through other elements.
Knowing that 2D array indexing is fast helps you explain why some algorithms are efficient and others are slow. It shows you understand how data is stored and accessed.
"What if we tried to find a value by searching every element in the 2D array? How would the time complexity change?"