0
0
Software Engineeringknowledge~5 mins

DRY (Don't Repeat Yourself) in Software Engineering - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: DRY (Don't Repeat Yourself)
O(n)
Understanding Time Complexity

Analyzing time complexity helps us see how following the DRY principle affects the speed of our code.

We want to know how avoiding repeated code impacts the number of steps the program takes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function calculateSum(arr) {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    sum += arr[i];
  }
  return sum;
}

function calculateAverage(arr) {
  let total = calculateSum(arr);
  return total / arr.length;
}
    

This code calculates the sum of numbers in an array and then uses that to find the average, reusing the sum calculation instead of repeating the loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A single loop that goes through the array once to sum all elements.
  • How many times: The loop runs exactly once per function call to calculateSum.
How Execution Grows With Input

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

Input Size (n)Approx. Operations
1010 steps to sum
100100 steps to sum
10001000 steps to sum

Pattern observation: The work grows evenly as the input grows; doubling input doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly with the size of the input array.

Common Mistake

[X] Wrong: "Calling the sum function twice is just as fast as calling it once."

[OK] Correct: Each call loops through the array, so calling it twice doubles the work and time.

Interview Connect

Understanding how reusing code affects time helps you write cleaner and faster programs, a skill valued in real projects and interviews.

Self-Check

"What if the sum calculation was repeated inside the average function instead of calling a separate function? How would the time complexity change?"