0
0
Javaprogramming~15 mins

One-dimensional arrays in Java - Time & Space Complexity

Choose your learning style8 modes available
scheduleTime Complexity: One-dimensional arrays
O(n)
menu_bookUnderstanding Time Complexity

When working with one-dimensional arrays, it is important to understand how the time to process them grows as the array gets bigger.

We want to know how the number of steps changes when the array size increases.

code_blocksScenario Under Consideration

Analyze the time complexity of the following code snippet.


int sumArray(int[] arr) {
    int sum = 0;
    for (int i = 0; i < arr.length; i++) {
        sum += arr[i];
    }
    return sum;
}
    

This code adds up all the numbers in a one-dimensional array and returns the total.

repeatIdentify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that visits each element in the array once.
  • How many times: Exactly once for each element in the array, so as many times as the array length.
search_insightsHow Execution Grows With Input

As the array gets bigger, the number of steps grows in a straight line with the size.

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

Pattern observation: Doubling the array size doubles the work needed.

cards_stackFinal Time Complexity

Time Complexity: O(n)

This means the time to sum the array grows directly with the number of elements.

chat_errorCommon Mistake

[X] Wrong: "Since the loop is simple, the time is constant no matter the array size."

[OK] Correct: Even a simple loop must run once per element, so more elements mean more steps.

business_centerInterview Connect

Understanding how loops over arrays scale is a key skill that helps you reason about many coding problems clearly and confidently.

psychology_altSelf-Check

"What if we changed the loop to run only half the array? How would the time complexity change?"