Lesson 1 · Unit 01
Growth, not seconds
Count loop runs: constant and linear time
What you practise
- Count loop runs
- O(1) and O(n)
- Worst case
- Big-O ignores machine speed
Try a question from this lesson
Pick one
A list holds 1,000 names and the target is not one of them. How many names does this function check?
def contains(names, target):
for name in names:
if name == target:
return True
return Falsefunction contains(names, target) {
for (const name of names) {
if (name === target) return true;
}
return false;
}function contains(
names: string[],
target: string,
): boolean {
for (const name of names) {
if (name === target) return true;
}
return false;
}Correct answer
1,000
Why
A missing target is the worst case: the loop must look at every name to be sure. The work grows in step with the list. That is called linear time.
TypeScript notenames: string[] and : boolean are type annotations. They are erased before the code runs; the JavaScript underneath is identical.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Big-O counts growth
Big-O describes how the number of steps grows as the input grows. It ignores how fast your machine is.
One loop over n items is O(n), linear: double the input and the steps double. Work that never depends on n is O(1), constant.
def first(items):
return items[0] # O(1)
def total(nums):
result = 0
for x in nums: # runs n times
result += x
return result # O(n)function first(items) {
return items[0]; // O(1)
}
function total(nums) {
let result = 0;
for (const x of nums) { // n times
result += x;
}
return result; // O(n)
}function first<T>(items: T[]): T {
return items[0]; // O(1)
}
function total(nums: number[]) {
let result = 0;
for (const x of nums) { // n times
result += x;
}
return result; // O(n)
}TypeScript notefirst<T> is generic: T stands for whatever the array holds, so first([7, 8]) returns a number and first(["a"]) a string.
9 more exercises in the app
- 2× type the answer
- 3× multiple choice
- 1× true or false
- 1× fill the blanks
- 1× match the pairs
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.