0
0
Goprogramming~5 mins

Program stability concepts in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Program stability concepts
O(n)
Understanding Time Complexity

Program stability means how well a program keeps working correctly as input size changes.

We want to know how the program's speed changes when it handles more data.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func stableProcess(data []int) int {
    result := 0
    for _, value := range data {
        if value%2 == 0 {
            result += value
        }
    }
    return result
}
    

This code sums all even numbers in a list of integers.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each item in the data list.
  • How many times: Once for every item in the list.
How Execution Grows With Input

As the list gets bigger, the program checks more numbers one by one.

Input Size (n)Approx. Operations
10About 10 checks
100About 100 checks
1000About 1000 checks

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

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the input size.

Common Mistake

[X] Wrong: "The program runs faster because it only adds even numbers."

[OK] Correct: The program still checks every number, so the time depends on the total list size, not just the even numbers.

Interview Connect

Understanding how a program's speed changes with input size shows you can write stable and predictable code.

Self-Check

"What if we changed the code to sum only numbers greater than 100? How would the time complexity change?"