Lesson 2 · Unit 02
The cost of moving
Cheap at the end, expensive at the front
What you practise
- Append and pop at the end are O(1)
- Insert/remove at the front shifts everything, O(n)
Try a question from this lesson
Pick one
Ten people sit in a row of ten chairs, with empty chairs after them. A newcomer must have the first chair. How many people move?
Correct answer
10
Why
Everyone shifts one chair along to free the first one. Arrays are the same: items sit side by side, so inserting at the front moves all n of them.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Ends are cheap, fronts are not
Adding or removing at the end of an array touches one slot: O(1).
At the front, every other item has to shift over by one: O(n).
nums = [1, 2, 3]
nums.append(4) # O(1)
nums.pop() # O(1)
nums.insert(0, 9) # O(n): all shift
nums.pop(0) # O(n): all shift
print(*nums)const nums = [1, 2, 3];
nums.push(4); // O(1)
nums.pop(); // O(1)
nums.unshift(9); // O(n): all shift
nums.shift(); // O(n): all shift
console.log(nums.join(" "));const nums = [1, 2, 3];
nums.push(4); // O(1)
nums.pop(); // O(1)
nums.unshift(9); // O(n): all shift
nums.shift(); // O(n): all shift
console.log(nums.join(" "));Python noteprint(*nums) unpacks the list into separate arguments, so it prints 1 2 3 rather than [1, 2, 3].
JavaScript notepush/pop work at the end, unshift/shift at the front.
TypeScript notepush/pop work at the end, unshift/shift at the front. pop() and shift() return number | undefined: the array may be empty.
Concept
Why append is (almost) free
Arrays keep spare room at the end. When it runs out, the array moves to a block twice the size: an O(n) copy, once. Then appends are instant again.
Averaged over many appends the cost is O(1) each. This is called amortised constant time.
9 more exercises in the app
- 1× match the pairs
- 2× type the answer
- 1× fill the blanks
- 3× multiple choice
- 1× true or false
- 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.