KISS (Keep It Simple) in Software Engineering - Time & Space Complexity
When we keep code simple, it often runs faster and is easier to understand. Analyzing time complexity helps us see how the cost of running code grows as it gets more complex.
We want to know how simplifying code affects how long it takes to run as input grows.
Analyze the time complexity of the following code snippet.
function sumArray(numbers) {
let total = 0;
for (let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
return total;
}
This code adds up all numbers in an array by going through each item once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element of the array once.
- How many times: Exactly as many times as there are items in the array.
As the array gets bigger, the number of steps grows in a straight line with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: Doubling the input doubles the work needed.
Time Complexity: O(n)
This means the time to run grows directly with the size of the input.
[X] Wrong: "Simpler code always runs instantly no matter the input size."
[OK] Correct: Even simple code takes more time if the input is bigger because it still needs to process each item.
Understanding how simple code scales helps you write clear and efficient solutions. This skill shows you can balance clarity with performance, which is valuable in real projects and interviews.
"What if we changed the loop to run nested loops over the array? How would the time complexity change?"