Explain why indexing is O(1) and inserting in the middle is O(n).
Use it when the question is about a position, a count of moves, or how a list grows. Signal words: the entry at a given position, insert or remove in the middle, how many entries move, the list grows as entries arrive.
Read or write at an index one address calculation, O(1).
Insert or delete at index i shift the entries after i by one slot. Start from the end for an insert, and from the start for a delete. That is n - i moves, O(n).
Append write at the end, and double the room when it is full. O(1) amortised.
It does not suit many edits at the front or in the middle of a long, ordered list. Rebuild in one pass, or use a different structure.
Cost: index O(1), end O(1) amortised, middle O(n), space O(n) with up to twice the room reserved.
In this lesson you see how an array sits in memory and what that means for cost. You learn why reading any index is cheap, why inserting in the middle is not, and why appending is cheap on average.
You work on the packing screen of an online store. Order tickets sit in an array, in the order the packers must handle them, and each ticket is a small record.
A nightly job puts rush orders ahead of the rest. On a busy night the array holds 100,000 tickets, and 30,000 rush tickets go to the front, one at a time. Moving one ticket to the next slot takes about 2 nanoseconds.
Your team lead says: The job must finish within a second. Insert the rush tickets and tell me whether it fits.
Here is a short test: five tickets, numbered 101 to 105. A rush ticket, 900, goes to place 2.
So the task is this: understand what one insert costs, and find a way to put 30,000 tickets in front without waiting seven seconds.
A row of numbered lockers stands in a corridor, all the same width. Locker 0 is at the door. To reach locker 73,000 you do not open the ones before it: you walk 73,000 locker-widths from the door. That is one calculation, so it takes the same time for every locker.
Now you want a new locker in the middle of the row. The row has no gaps, so every locker after that place must slide one width along. The lockers are the slots of an array, the number is the index, and the slide is a move.
Like lockers of equal width: you reach any locker by walking its number of widths, and a new one in the middle slides every later locker along.
Before you write code, insert the rush ticket into the five tickets by hand. It shows what an insert does.
Solve it by hand: Five tickets: insert a rush ticket at place 2. The hand-solve sheet loads in your browser.
You cannot write into place 2 straight away. It holds ticket 103, which you would lose. So you copy the entries right, one place each, starting from the last.
The tickets are 101, 102, 103, 104 and 105. The rush ticket 900 goes to place 2. A copy has one extra slot at the end.
| Step | Copy | List after the step | Moves so far |
|---|---|---|---|
| 1 | place 4 to place 5 | [101, 102, 103, 104, 105, 105] | 1 |
| 2 | place 3 to place 4 | [101, 102, 103, 104, 104, 105] | 2 |
| 3 | place 2 to place 3 | [101, 102, 103, 103, 104, 105] | 3 |
| 4 | write 900 at place 2 | [101, 102, 900, 103, 104, 105] | 3 |
You made 3 moves, one for each ticket from place 2 on. In general an insert at index i of n entries makes n - i moves.
Start with a correct version. It inserts one ticket at a time, shifting from the end.
def insert_at(values, index, value):
items = list(values) + [0]
for j in range(len(values), index, -1): # shift from the end
items[j] = items[j - 1]
items[index] = value
return itemsThis is correct. The job calls it 30,000 times with index 0.
Now check the real size.
The array holds 100,000 tickets, 30,000 rush tickets go to the front one by one, and a move takes 2 nanoseconds.
Here is the count:
So the job takes about seven times the one second it has.
Predict the cost
Q One insert at the front of an array of 100,000 tickets moves every ticket one slot right. How many moves is that?
Answer: C
Every entry from index 0 to the end shifts one place, so an insert at index 0 moves all n entries. For n = 100,000 that is 100,000 moves.
The first attempt is correct, but it pays the full shift 30,000 times. Now look at how the array is stored, to see where the cost comes from.
An array is one block of memory cut into equal slots, side by side. Each slot holds one entry. The array only needs to remember where the block starts, which is the base address.
The address of the entry at index i is base + i × size, where size is the width of one slot. Take a base of 5000 and 4 bytes for each slot:
| Index | Address |
|---|---|
| 0 | 5000 |
| 1 | 5004 |
| 2 | 5008 |
| 5 | 5020 |
| 73,000 | 297,000 |
The calculation is one multiplication and one addition. It costs the same for index 5 and for index 73,000, so reading or writing any index is O(1).
The same layout explains the insert. The slots have no gaps, so to open a slot at index i you must move every entry from i onwards. Here is how many entries move for an array of 100,000:
| Edit | At index | Entries moved |
|---|---|---|
| Insert | 0 | 100,000 |
| Insert | 50,000 | 50,000 |
| Insert | 99,999 | 1 |
| Insert | 100,000 (the end) | 0 |
| Delete | 0 | 99,999 |
| Delete | 50,000 | 49,999 |
| Delete | 99,999 (the last) | 0 |
An edit at the end is free, and an edit at the front is the worst. A middle edit costs O(n).
Exercise · Put it in order: Close the gap after a delete. Arrange the lines into a function that returns the array without the entry at the index: copy what is before it, then move everything after it one place left.
def delete_at(values, index):
n = len(values)
items = [0] * (n - 1)
for j in range(index):
items[j] = values[j]
for j in range(index + 1, n):
items[j - 1] = values[j]
return items
for j in range(index, n):Two ways avoid that cost for the rush tickets. First, build one new array: write the 30,000 rush tickets, then the old 100,000. That is 130,000 writes in one pass, against 3,449,985,000 moves, which is 26,538 times fewer. Second, when order does not matter, delete by copying the last entry over the deleted one: 1 move.
Appending looks free, but an array has a fixed size. A dynamic array keeps spare room. When it is full, it allocates a bigger block and copies every entry across.
If the new block has one more slot, every later append copies the whole array again. If the new block has twice the room, a full array of k entries copies k entries only once for the next k appends.
Race: Growing by one slot against doubling. The operation counter loads in your browser.
At 1,000 appends, growing by one slot copies 499,500 entries and doubling copies 1,023. At 100,000 appends the counts are 4,999,950,000 against 131,071.
A dynamic array that doubles its room when full copies every entry across: copies of 1, 2, 4 and 8 mean ten appends copy only fifteen entries.
The array starts with room for 1 entry. You append 10 entries, and it doubles each time it is full. The player stops at five steps and asks you to predict.
Dry run: Predict each step: ten appends to a growing array. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row.
| Append | Array full? | Slots after | Entries copied in all |
|---|---|---|---|
| 1 | no | 1 | 0 |
| 2 | yes, 1 entry | 2 | 1 |
| 3 | yes, 2 entries | 4 | 3 |
| 5 | yes, 4 entries | 8 | 7 |
| 9 | yes, 8 entries | 16 | 15 |
| 10 | no | 16 | 15 |
Ten appends made 15 copies. Look at the pattern. The copies are 1, 2, 4 and 8, each double the last. The last copy is about as large as all the earlier ones together, so the total stays below 2 for each append.
Here are the copies counted by running the template for larger arrays.
| Appends | Doubling: entries copied | Per append | Grow by one: entries copied |
|---|---|---|---|
| 1,000 | 1,023 | 1.02 | 499,500 |
| 100,000 | 131,071 | 1.31 | 4,999,950,000 |
| 1,000,000 | 1,048,575 | 1.05 | 499,999,500,000 |
The copies for doubling stay below 2 per append at any size. So the average cost of an append is O(1), even though one append in a million costs a long copy. This is called amortised O(1).
Doubling is the easiest rule to count, but each library picks its own factor. Any constant factor above 1 keeps an append O(1) amortised. A smaller factor wastes less room and copies more often.
| List type | Growth when full | Where the figure comes from |
|---|---|---|
CPython list (3.11.6) |
about 1.125 times at large sizes, plus a few slots | a run that watched sys.getsizeof |
Java ArrayList (OpenJDK) |
1.5 times | the library source |
C++ std::vector |
not fixed by the standard; commonly 2 or 1.5 times | depends on the library |
| JavaScript arrays | depends on the engine | not part of the language |
On CPython 3.11.6, 1,000,000 appends grew the list's block 86 times, ending with room for 1,056,084 entries. If every growth copied every entry, that is 8,445,096 copies, about 8.4 for each append. The allocator can sometimes extend a block where it is, so the real count can be lower.
Here is the rule that keeps an array correct. Every line of both templates exists to protect it.
Entries sit in contiguous slots, so index i is at base + i × size; an edit in the middle must move every entry after it.
At the start the slots are contiguous, because the array is one block. An insert keeps them contiguous by shifting the tail, and an append keeps them contiguous by copying into a bigger block when the block is full.
Nothing else is allowed to change: no entry before the edit moves, and the order of the entries stays the same.
Use it when the question is about a position, a count of moves, or how a list grows. Signal words: the entry at a given position, insert or remove in the middle, how many entries move, the list grows as entries arrive.
Read or write at an index: one address calculation, O(1).
Insert or delete at index i: shift the entries after i by one slot. Start from the end for an insert, and from the start for a delete. That is n - i moves, O(n).
Append: write at the end, and double the room when it is full. O(1) amortised.
It does not suit many edits at the front or in the middle of a long, ordered list. Rebuild in one pass, or use a different structure.
Cost: index O(1), end O(1) amortised, middle O(n), space O(n) with up to twice the room reserved.
def insert_at(values, index, value):
# [1] Make room: a copy with one more slot at the end.
items = list(values) + [0]
n = len(values)
# [2] Shift the tail right by one place, starting from the last entry, so that nothing is overwritten before it is read.
for j in range(n, index, -1):
items[j] = items[j - 1]
# [3] Write the new value into the gap.
items[index] = value
# [4] Return the longer list.
return itemspublic int[] insertAt(int[] values, int index, int value) {
// [1] Make room: a copy with one more slot at the end.
int n = values.length;
int[] items = new int[n + 1];
for (int i = 0; i < n; i++) {
items[i] = values[i];
}
// [2] Shift the tail right by one place, starting from the last entry, so that nothing is overwritten before it is read.
for (int j = n; j > index; j--) {
items[j] = items[j - 1];
}
// [3] Write the new value into the gap.
items[index] = value;
// [4] Return the longer list.
return items;
}vector<int> insertAt(vector<int>& values, int index, int value) {
// [1] Make room: a copy with one more slot at the end.
vector<int> items = values;
items.push_back(0);
int n = (int)values.size();
// [2] Shift the tail right by one place, starting from the last entry, so that nothing is overwritten before it is read.
for (int j = n; j > index; j--) {
items[j] = items[j - 1];
}
// [3] Write the new value into the gap.
items[index] = value;
// [4] Return the longer list.
return items;
}function insertAt(values, index, value) {
// [1] Make room: a copy with one more slot at the end.
const items = [...values, 0];
const n = values.length;
// [2] Shift the tail right by one place, starting from the last entry, so that nothing is overwritten before it is read.
for (let j = n; j > index; j--) {
items[j] = items[j - 1];
}
// [3] Write the new value into the gap.
items[index] = value;
// [4] Return the longer list.
return items;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: The ticket that fills the queue. This insert should shift the tail right and write the new ticket into the gap. At the front of [1, 2, 3] it returns a list full of copies. Which line is wrong?
def insert_at(values, index, value):
items = list(values) + [0]
n = len(values)
for j in range(index + 1, n + 1):
items[j] = items[j - 1]
items[index] = value
return itemsTo insert at an index, copy the last entry one slot right first, work back towards the index, then write the new value into the gap.
def count_copies(appends):
# [1] Start with room for one entry and nothing stored.
capacity = 1
size = 0
copies = 0
# [2] Append one entry at a time.
for _ in range(appends):
# [3] When the array is full, allocate twice the room and copy every stored entry across.
if size == capacity:
copies += size
capacity *= 2
# [4] Store the new entry in the next free slot.
size += 1
# [5] Return how many entries were copied in all.
return copiespublic long countCopies(int appends) {
// [1] Start with room for one entry and nothing stored.
long capacity = 1;
long size = 0;
long copies = 0;
// [2] Append one entry at a time.
for (int a = 0; a < appends; a++) {
// [3] When the array is full, allocate twice the room and copy every stored entry across.
if (size == capacity) {
copies += size;
capacity *= 2;
}
// [4] Store the new entry in the next free slot.
size++;
}
// [5] Return how many entries were copied in all.
return copies;
}long long countCopies(int appends) {
// [1] Start with room for one entry and nothing stored.
long long capacity = 1;
long long size = 0;
long long copies = 0;
// [2] Append one entry at a time.
for (int a = 0; a < appends; a++) {
// [3] When the array is full, allocate twice the room and copy every stored entry across.
if (size == capacity) {
copies += size;
capacity *= 2;
}
// [4] Store the new entry in the next free slot.
size++;
}
// [5] Return how many entries were copied in all.
return copies;
}function countCopies(appends) {
// [1] Start with room for one entry and nothing stored.
let capacity = 1;
let size = 0;
let copies = 0;
// [2] Append one entry at a time.
for (let a = 0; a < appends; a++) {
// [3] When the array is full, allocate twice the room and copy every stored entry across.
if (size === capacity) {
copies += size;
capacity *= 2;
}
// [4] Store the new entry in the next free slot.
size++;
}
// [5] Return how many entries were copied in all.
return copies;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Break it: Find the run where growing by one costs more. This version makes room for one more entry when the array is full, instead of doubling. Find a number of appends where it copies more entries than the doubling version.
def count_copies(appends):
capacity = 1
size = 0
copies = 0
for _ in range(appends):
if size == capacity:
copies += size
capacity += 1
size += 1
return copiesThe two templates answer two kinds of question. You can pick before you write any code.
Then check the ends: what happens at index 0, at index n, and on an empty array?
| Situation | Cost | Why |
|---|---|---|
| Read the entry at index 73,000 | O(1) | One address calculation |
| Append to a dynamic array | O(1) amortised | Doubling copies fewer than 2 entries per append |
| Insert at the front | O(n) | Every entry shifts |
| Delete the last entry | O(1) | Nothing after it |
| Many edits, order must stay | One rebuild pass | n + m writes beat m × n moves |
A music app keeps a queue of 6 song numbers: 31, 32, 33, 34, 35 and 36. The listener adds song 77 as the third song to play, which is index 2.
The array has 6 entries, and only the 4 entries from index 2 on shift.
| Step | j | Copy | What happens |
|---|---|---|---|
| 1 | 6 | place 5 to place 6 | 36 moves right |
| 2 | 5 | place 4 to place 5 | 35 moves right |
| 3 | 4 | place 3 to place 4 | 34 moves right |
| 4 | 3 | place 2 to place 3 | 33 moves right |
Then 77 is written at place 2. The queue is 31, 32, 77, 33, 34, 35 and 36, after 4 moves, which is 6 - 2.
Real data brings edge cases.
For values = [] and index = 0, there is nothing to shift. The shifting loop runs from 0 down to 0, so it does not run, and the result is [5] for the value 5.
For values = [1, 2, 3] and index = 3, the index equals the length. The loop range(3, 3, -1) is empty, so there are no moves, and the result is [1, 2, 3, 9]. An insert at the end costs nothing.
For values = [1, 2, 3] and index = 0, all 3 entries move, and the result is [9, 1, 2, 3]. This is the worst case: n moves.
For appends = 1, the array has room for 1 entry, so nothing is copied: 0 copies. For appends = 2, the second append finds the array full and copies 1 entry: 1 copy.
This version loops for j in range(index + 1, n + 1) and copies items[j] = items[j - 1]. Each copy overwrites the entry that the next copy needs.
Counterexample: values = [1, 2, 3], index = 0, value = 9. The version returns [9, 1, 1, 1]: the 1 is copied over the 2, then over the 3. The correct version returns [9, 1, 2, 3].
The fix is to start at the last entry and move towards the index.
This version loops for j in range(n, index + 1, -1), so it never copies into place index + 1. The entry that belongs there stays as it was.
Counterexample: values = [10, 20, 30], index = 1, value = 99. The version returns [10, 99, 30, 30], and the 20 is lost. The correct loop, range(n, index, -1), returns [10, 99, 20, 30].
The last copy goes into place index + 1, so the loop must stop after it: the stop value is index, not index + 1.
Shifting from the front overwrites entries before they are read: inserting nine at the front of one, two, three returns nine, one, one, one.
This version allocates one extra slot each time the array is full, so every append after that is a full copy. It is correct, and it is quadratic.
Counterexample: for 100,000 appends it copies 4,999,950,000 entries. Doubling copies 131,071. For 1,000,000 appends the counts are 499,999,500,000 and 1,048,575.
Grow by a constant factor, such as 2, not by a constant amount.
This version reasons that arrays have O(1) access, so the 30,000 front inserts take 30,000 steps. It confuses reading an index with editing at an index.
Counterexample: reading costs 1 step, and one front insert costs 100,000 moves. The job makes 3,449,985,000 moves, and not 30,000.
Ask what moves, not only what is addressed.
The app also keeps a feed where every new item goes to the front, and the feed reaches 100,000 items. Inserting each item at the front of an array makes 4,999,950,000 moves in all.
An array is the wrong tool for a front-heavy list. A double-ended queue or a linked list adds at the front in O(1), and later lessons build both.
Your team lead brings four product changes. Each one asks what must move.
A set of active sessions is stored in an array, and the order is not used. Delete session i by copying the last entry into place i and shrinking the array by one. That is 1 move, not n - i.
A screen shows the latest 50 events. Keep an array of 50 slots and a start index, and write each new event over the oldest one. Nothing shifts: this is a circular buffer.
A hall has 40 rows of 25 seats, stored in one array row by row. Seat (row, col) is at index row × 25 + col. The same address rule works with two indices.
After a sale ends the array holds 1,000 entries in room for 1,000,000. Halve the room when the array is a quarter full, so that the memory is returned and the cost of shrinking is amortised too.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate why reading an array index is O(1) while inserting in the middle is O(n). Then say what an append costs on average. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have counted it.
An array is one block of equal slots, so the entry at index i is at base plus i times the slot size. That is one calculation, so any read or write is O(1).
The slots have no gaps, so an insert at index i moves every entry from i on, which is n minus i moves. At the front of 100,000 entries that is 100,000 moves.
A dynamic array grows by a constant factor when full. With doubling, an append costs about 1 copy on average, so it is O(1) amortised.
An array stores its entries side by side in equal slots, so the address of index i is the base plus i times the slot size. A read or a write at any index is one calculation: O of 1.
Because the slots have no gaps, an insert or a delete at index i moves every entry after it. That is n minus i moves, so the middle is O of n and the front is the worst case. I shift from the end for an insert, so nothing is overwritten before it is read.
Appending uses spare room. When the array is full, a dynamic array grows by a constant factor, say double, and copies every entry once. Ten appends copy 15 entries, and a million appends copy about a million, so an append is O of 1 amortised.
If there are many edits, I look for one pass that rebuilds the array, or for a structure that fits the edits better.
Checkpoint · Memory layout
Q1/3 An array starts at address 5000 and each slot is 4 bytes wide. At which address is the entry at index 5?
Answer: C
The address is base + i × size, which is 5000 + 5 × 4 = 5020. Index 0 is at 5000 and index 1 is at 5004.
Q2/3 Why does reading the entry at index 73,000 cost the same as reading index 5?
Answer: C
The slots are equal in width and side by side, so the address is base + i × size. The calculation does not depend on i.
Q3/3 An array holds 100,000 entries. How many entries move when you insert at index 0?
Answer: C
Every entry from index 0 on shifts one slot right, so all n entries move. The array being full or not does not change the count.
Checkpoint · Inserting and deleting
Q1/3 An array holds 100,000 entries. How many entries move when you insert at index 100,000, the end?
Answer: C
There are no entries after the end, so nothing shifts. An insert at index i moves n - i entries, and n - n is 0.
Q2/3 You insert at index 2 of a list. In which direction do you copy the entries, and why?
Answer: B
Copying from the front writes over the entry the next copy needs. Start at the last entry and work back to the index.
Q3/3 The array holds sessions in no particular order. What is the cheapest way to delete the session at index i?
Answer: B
If order does not matter, the last entry fills the gap, and only one entry moves. The slots stay contiguous.
Checkpoint · Growing
Q1/3 A dynamic array doubles its room when it is full, and starts with room for 1 entry. How many entries have been copied after 10 appends?
Answer: C
The array is full at the 2nd, 3rd, 5th and 9th appends and copies 1, 2, 4 and 8 entries: 15 in all.
Q2/3 Why is an append to a doubling array O(1) amortised?
Answer: B
The copies are 1, 2, 4, 8 and so on, and their sum is less than twice the last one. So the cost per append averages below 2 copies.
Q3/3 An array grows by one slot every time it is full. About how many entries are copied in all for 100,000 appends?
Answer: C
Each append copies the whole array, so the total is 1 + 2 + ... + 99,999, which is n(n - 1)/2 = 4,999,950,000. Doubling copies only 131,071.
Checkpoint · Rows and columns
Q A hall has 40 rows of 25 seats, stored in one array row by row. At which index is the seat in row 3, column 7? Rows and columns start at 0.
Answer: B
The index is row × seats in a row + column. Each full row before row 3 holds 25 seats, so 3 × 25 = 75, plus 7 gives 82.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Rotate the dashboard tiles | Observe | Easy | Moving entries without losing any |
| 2 | Rows and columns of a seating grid | Stream | Easy | Index arithmetic on a flat array |
| 3 | Ids missing from the roster | Rides | Easy | Using index and value together |
| 4 | Is the rota a rotated sorted list | Freight | Easy | One scan, one wrap-around check |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.