0
0
NumPydata~5 mins

2D array indexing (row, col) in NumPy - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: 2D array indexing (row, col)
O(1)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Accessing a single element by its row and column index.
  • How many times: Exactly once for this access.
How Execution Grows With Input

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 101
100 x 1001
1000 x 10001

Pattern observation: The time to access one element stays the same even if the array grows larger.

Final Time Complexity

Time Complexity: O(1)

This means accessing an element by row and column is done in constant time, no matter the array size.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if we tried to find a value by searching every element in the 2D array? How would the time complexity change?"