Lesson 1 · Unit 02
Index and scan
Jump to a slot in O(1), search in O(n)
What you practise
- O(1) indexing, last index n-1, linear scan for max/min, out-of-range behaviour per language
Try a question from this lesson
Pick one
The array has three items. What happens when this runs?
nums = [10, 20, 30]
print(nums[3])const nums = [10, 20, 30];
console.log(nums[3]);const nums = [10, 20, 30];
console.log(nums[3]);Correct answer
It raises an IndexError
It prints undefined
It prints undefined
Why
Index 3 is one past the end: the valid indexes are 0, 1 and 2. Python refuses with an IndexError. JavaScript and TypeScript hand back undefined, which hides the bug until later.
TypeScript noteTypeScript still types nums[3] as number. The compiler option noUncheckedIndexedAccess makes it number | undefined, which is the truth.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Numbered boxes
An array stores its items side by side. To read item i the computer works out where box i sits and jumps there: indexing is O(1).
With n items, the indexes run from 0 to n - 1. There is no box n.
nums = [10, 20, 30]
print(nums[0]) # 10
print(nums[len(nums) - 1]) # 30const nums = [10, 20, 30];
console.log(nums[0]); // 10
console.log(nums[nums.length - 1]); // 30const nums = [10, 20, 30];
console.log(nums[0]); // 10
console.log(nums[nums.length - 1]); // 30Python noteNegative indexes count from the end: nums[-1] is the last item.
TypeScript noteconst nums = [10, 20, 30] is inferred as number[]. const stops you reassigning nums, not changing its items.
9 more exercises in the app
- 3× type the answer
- 1× true or false
- 1× fill the blanks
- 2× multiple choice
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.