Big-O for
Arrays
Understand how loops and common array operations scale with input size \( n \): from constant-time lookups to quadratic nested loops.
What is Big-O Notation?
Big-O describes how the number of operations grows as the input size \( n \) increases. It answers the question: "If my array doubles in size, how much slower does my code get?"
Why Does Efficiency Matter?
Visualizing Growth Rates
\( O(1) \): Constant Time
An operation is \( O(1) \) when it takes the same number of steps regardless of the array's size. The array could have 10 or 10 million elements: the cost is identical.
\( O(n) \): Linear Time
An operation is \( O(n) \) when it must visit each element once. Doubling the array size doubles the work.
\( O(n^2) \): Quadratic Time
Nested loops that both depend on \( n \) produce \( O(n^2) \) complexity. Each element is compared against every other element.
push/pop vs shift/unshift
The Loop Counting Rule
How to Analyze Any Function
Example 1: Sum an Array
Example 2: Hidden Nested Loop
Example 3: Sequential Loops
Array Methods Cheat Sheet
| Method | Big-O | Why |
|---|---|---|
| arr[i] | \( O(1) \) | Direct index access |
| push / pop | \( O(1) \) | Modify end only |
| shift / unshift | \( O(n) \) | Re-indexes all elements |
| splice (middle) | \( O(n) \) | Shifts elements after target |
| indexOf / includes | \( O(n) \) | Linear scan worst case |
| map / filter / reduce | \( O(n) \) | Visits every element |
| sort | \( O(n \log n) \) | Comparison-based sort |
Common Mistakes
Question 1 of 5
What is the time complexity of accessing arr[500] in an array of 10,000 elements?
Question 2 of 5
A function uses a for-loop that calls .indexOf() on the same array during each iteration. What is the overall time complexity?
Question 3 of 5
Why is .unshift() considered \( O(n) \) while .push() is \( O(1) \)?
Question 4 of 5
A function has three consecutive loops: .map(), then .filter(), then .reduce(). Each processes the full array. What is the total Big-O?
Question 5 of 5
Consider this function:
function mystery(arr) {
const seen = new Set();
for (const item of arr) {
if (seen.has(item)) return true;
seen.add(item);
}
return false;
}
What is the time complexity of mystery()?