Arrays
The structure behind every list in your code: elements side by side, instant access by index, but costly to squeeze a new value into the middle.
- Explain why indexed access is constant time
- Trace the element shifting caused by an insert or delete
- Choose between an array and a linked list for a given task
Finish first
Cost at a glance
- access
- O(1)
- search
- O(n)
- insert
- O(n)
- delete
- O(n)
Topic contents
Lesson 1 of 2
Side by side in memory
An array stores its elements in one continuous block, in order. Because every element is the same size and the block is unbroken, the computer can jump straight to element 5 instead of hunting from the start. That is why array access is O(1).
The cost shows up when you change the shape. There is no gap to insert into, so making room means sliding every element after the insertion point one place to the right. Try it in the lab and count the moves.
Exam questions often ask: fast lookup or fast insert in the middle? Arrays win lookup. Linked lists, coming soon, win insert at a known position.
Array operations
Insert, delete, search and traverse, one controllable step at a time, with the shifting made visible.
Array operations
access O(1) · insert/delete/search O(n)Start
Traversal visits every element exactly once, in index order.
Lesson 2 of 2
Watch the shift happen
Use the visualizer to insert a value at index 2. Step through it one frame at a time and notice the order of events: the last element moves right first, then the one before it, and so on back to the insertion point. If you shifted left-to-right instead, you would overwrite values you still needed.
Then delete at index 2 and watch the direction reverse, elements move left to close the gap, and the array shrinks by one.
Worked examples
Read the code, then change it
Copy any example into the playground and break it on purpose. That is the fastest way to learn what each line is holding up.
function insertAt(values, index, value) {
// Walk backwards so we never overwrite an element we still need.
for (let i = values.length; i > index; i--) {
values[i] = values[i - 1];
}
values[index] = value;
return values;
}
console.log(insertAt([10, 20, 30, 40], 2, 25));def insert_at(values, index, value):
values.append(None)
for i in range(len(values) - 1, index, -1):
values[i] = values[i - 1]
values[index] = value
return values
print(insert_at([10, 20, 30, 40], 2, 25))Practice
Work these out yourself
No answer key here on purpose: these are the questions worth thinking through before you move on. Open one and work it out.
0/3 attemptedAssessment
Check your understanding
Answer each question, then read the explanation. That is where the learning is.
Finished this topic?
0 of 2 lessons marked done. Marking the topic complete ticks the rest.
