0
0
DSA Pythonprogramming~5 mins

Array Traversal Patterns in DSA Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Array Traversal Patterns
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the array gets bigger, the number of print actions grows the same way.

Input Size (n)Approx. Operations
1010 prints
100100 prints
10001000 prints

Pattern observation: The work grows directly with the size of the array.

Final Time Complexity

Time Complexity: O(n)

This means if the array doubles in size, the time to go through it also doubles.

Common Mistake

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

Interview Connect

Understanding how simple loops grow with input size is a key skill that helps you analyze more complex code easily.

Self-Check

"What if we nested another loop inside to compare every element with every other? How would the time complexity change?"