🎉 All 30 days are live — the full DSA-30 course, from Big-O to System Design. See the roadmap →

Basic Operations

Reading arr[999] from a million-element array is instant. So is reading arr[0]. But inserting a value at arr[0] is one of the slowest things you can do to an array. Same array, same one-element operation — why is one free and the other expensive?

The answer is the whole personality of the array, and it’s written in the operation costs below. Every data structure is defined by what it makes cheap and what it makes painful:

OperationTimeSpaceNotes
Access by indexO(1)O(1)Direct calculation using address formula
Search (unsorted)O(n)O(1)Must check every element
Search (sorted)O(log n)O(1)Binary search
Insert at endO(1)O(1)O(n) if array needs resizing
Insert at positionO(n)O(1)Must shift elements right
Delete at endO(1)O(1)Just decrement size
Delete at positionO(n)O(1)Must shift elements left
Find min/maxO(n)O(1)Must scan entire array
Predict first
To insert a value at index 0 of a 1,000-element array, how many existing elements have to move?
Access by index is O(1) but search (unsorted) is O(n). What explains the difference?

Rebuild the insert from memory

You saw the code above. Now recall the one line that does the real work. To insert at pos, you walk from the end backward, copying each element one slot right — fill in the shift:

python · fill in the blanks0/1 hints
def insert_at(arr, pos, x):
arr.append(None) # grow by one slot
for i in range(len(arr) - 1, pos, -1):
# ??? the shift that opens a hole at pos
arr[pos] = x # drop the new value into the hole
return arr

Why walk backward (from the end toward pos)? If you copied front-to-back you’d overwrite values before moving them. Going right-to-left, each slot you write into has already been vacated. That’s the same shifting that makes the operation O(n).

Quick Check

What is the time complexity of inserting an element at the beginning of an array of size n?
You need a structure where you frequently insert/remove at the FRONT. Is a plain array a good fit?

This builds on memory representation — the contiguous layout is exactly what makes indexing O(1) and shifting O(n). Next: array algorithms, where these primitives combine into the techniques (two pointers, prefix sums, sliding window) the rest of the course leans on.

Finished this page?