0
0
NumPydata~5 mins

np.where() for conditional selection in NumPy - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: np.where() for conditional selection
O(n)
Understanding Time Complexity

We want to understand how the time to run np.where() changes as the size of the input array grows.

Specifically, how does the work inside np.where() scale with bigger arrays?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
result = np.where(arr > 3, arr, 0)

This code checks each element in arr. If the element is greater than 3, it keeps it; otherwise, it replaces it with 0.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking each element of the array against the condition.
  • How many times: Once for every element in the array.
How Execution Grows With Input

As the array gets bigger, the number of checks grows directly with the number of elements.

Input Size (n)Approx. Operations
10About 10 checks
100About 100 checks
1000About 1000 checks

Pattern observation: The work grows in a straight line with the input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to run np.where() grows directly in proportion to the number of elements in the array.

Common Mistake

[X] Wrong: "np.where() runs in constant time no matter the array size."

[OK] Correct: The function must check each element to decide what to output, so it takes longer with bigger arrays.

Interview Connect

Understanding how array operations scale helps you write efficient code and explain your choices clearly in real projects or interviews.

Self-Check

"What if we used np.where() on a 2D array instead of a 1D array? How would the time complexity change?"