Why patterns matter for safety in Typescript - Performance Analysis
When we write code, certain patterns repeat many times. Understanding how these patterns affect the time it takes for code to run helps us keep programs safe and efficient.
We want to know how the work grows as the input gets bigger, so our code stays reliable and fast.
Analyze the time complexity of the following code snippet.
function checkPattern(arr: number[]): boolean {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === 0) {
return true;
}
}
return false;
}
This code checks if the number 0 appears anywhere in the array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array elements one by one.
- How many times: Up to the length of the array, stopping early if 0 is found.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows directly with the size of the input array.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "The code always checks every item no matter what."
[OK] Correct: The code stops early when it finds 0, so sometimes it does less work than the full array length.
Knowing how patterns like loops affect time helps you explain your code clearly and shows you understand how to keep programs safe and efficient.
"What if we changed the code to check for every zero and count them instead of stopping early? How would the time complexity change?"