0
0
R Programmingprogramming~5 mins

Useful vector functions (length, sum, mean) in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Useful vector functions (length, sum, mean)
O(n)
Understanding Time Complexity

We want to know how the time needed to run vector functions changes as the vector gets bigger.

How does the work grow when using length, sum, or mean on a vector?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


# Create a numeric vector
vec <- c(1, 2, 3, 4, 5)

# Get the length of the vector
len <- length(vec)

# Calculate the sum of the vector elements
s <- sum(vec)

# Calculate the mean of the vector elements
m <- mean(vec)
    

This code finds how many items are in the vector, adds them all up, and then finds their average.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: sum() and mean() go through each item in the vector once.
  • How many times: They look at every element one time each.
  • length() operation: Just reads the vector size without looping.
How Execution Grows With Input

As the vector gets bigger, sum() and mean() take longer because they check each number once.

Input Size (n)Approx. Operations
10About 10 additions for sum and mean
100About 100 additions
1000About 1000 additions

Pattern observation: The work grows directly with the number of items; doubling items doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to sum or average grows in a straight line with the number of elements.

Common Mistake

[X] Wrong: "length() takes as long as sum() or mean() because it counts items one by one."

[OK] Correct: length() just reads the stored size quickly without checking each element, so it runs very fast no matter the vector size.

Interview Connect

Understanding how simple vector functions scale helps you reason about performance in data tasks and shows you can think about efficiency clearly.

Self-Check

"What if we used a function that squared each element before summing? How would the time complexity change?"