0
0
NumPydata~5 mins

Combining conditions in NumPy - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Combining conditions
O(n)
Understanding Time Complexity

We want to see how the time needed changes when we combine conditions in numpy arrays.

How does checking multiple conditions together affect the work done?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

import numpy as np

arr = np.random.randint(0, 100, size=1000)
result = (arr > 20) & (arr < 80)
filtered = arr[result]

This code creates an array, checks which elements are between 20 and 80, and selects those elements.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking each element against two conditions and combining results.
  • How many times: Once for each element in the array (n times).
How Execution Grows With Input

As the array gets bigger, the number of checks grows in direct proportion.

Input Size (n)Approx. Operations
10About 20 checks (2 per element)
100About 200 checks
1000About 2000 checks

Pattern observation: The work doubles if the input size doubles because each element is checked twice.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the number of elements checked.

Common Mistake

[X] Wrong: "Combining two conditions makes the code run twice as slow in a complex way."

[OK] Correct: Actually, each element is checked a fixed number of times, so the time grows simply with the number of elements, not in a complicated way.

Interview Connect

Understanding how combining conditions affects time helps you write clear and efficient data checks in real projects.

Self-Check

What if we used three conditions combined with & instead of two? How would the time complexity change?