Sub topic 3
Array operations: access, search, insert, delete
This chapter assumes you know how an array is laid out in contiguous memory and how the address of a[i] is computed from the base address and element size. It also assumes you can read Big-O notation. Here we count what each basic operation costs and where the common mistakes are.
Access by index
Access reads or overwrites a[i]. The machine computes base + i * size and goes straight to that address, so the cost does not depend on n.
- Time: O(1) for read and for write.
- Extra space: O(1).
This is why arrays are the default choice when you need random access. The cost holds only when the array is contiguous and every element has the same size.
Search
Search finds the position of a key x.
Linear search
Linear search scans from index 0 until it finds x or runs out of elements. It works on any array, sorted or not.
def linear_search(a, x):
for i in range(len(a)):
if a[i] == x:
return i
return -1- Best case: O(1), when the key is at index 0.
- Worst case: O(n), when the key is last or absent. This takes n comparisons.
- Average case for a successful search with equally likely positions: (n + 1) / 2 comparisons, which is O(n).
Binary search
Binary search needs a sorted array. It compares x with the middle element and discards half of the range each step.
def binary_search(a, x):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == x:
return mid
if a[mid] < x:
lo = mid + 1
else:
hi = mid - 1
return -1- Time: O(log n) in the worst case. The range halves each iteration, so at most floor(log2 n) + 1 comparisons are needed.
- Extra space: O(1) for the iterative version.
In languages with fixed-width integers, (lo + hi) / 2 can overflow for very large arrays. Writing lo + (hi - lo) / 2 avoids that. Python integers do not overflow, so the code above is safe as written.
Insert
Inserting into an array means making room. Elements to the right of the insertion point must each shift one position right. The loop must run from the end toward the insertion point. If it runs forward, it overwrites elements that have not been moved yet.
def insert_at(a, size, pos, value):
# a has spare capacity; size is the number of elements in use
if size == len(a):
raise OverflowError('array full')
for i in range(size, pos, -1):
a[i] = a[i - 1]
a[pos] = value
return size + 1
buf = [10, 20, 40, 50, None, None]
n = insert_at(buf, 4, 2, 30)
print(buf[:n]) # [10, 20, 30, 40, 50]The number of shifts is size - pos.
| Insert position | Shifts | Case |
|---|---|---|
| End (`pos = size`) | 0 | Best, O(1) |
| Middle | about n / 2 on average | O(n) |
| Front (`pos = 0`) | n | Worst, O(n) |
If the insertion position is chosen uniformly among the n + 1 possible slots, the average number of shifts is n / 2.
Delete
Deleting at position pos closes the gap. Elements to the right of pos shift one position left. This time the loop runs forward, from pos toward the end.
def delete_at(a, size, pos):
if pos < 0 or pos >= size:
raise IndexError('bad position')
for i in range(pos, size - 1):
a[i] = a[i + 1]
a[size - 1] = None
return size - 1
buf = [10, 20, 30, 40, 50]
n = delete_at(buf, 5, 1)
print(buf[:n]) # [10, 30, 40, 50]The number of shifts is size - 1 - pos.
- Delete the last element: 0 shifts, O(1).
- Delete the first element: n - 1 shifts, O(n).
If you do not care about order, there is a shortcut. Copy the last element into the gap and shrink the size by one. This deletes in O(1) but changes the order of elements.
Operations on sorted arrays
Sorting changes the costs of some operations.
| Operation | Unsorted array | Sorted array |
|---|---|---|
| Access by index | O(1) | O(1) |
| Search | O(n) | O(log n) with binary search |
| Insert | O(1) at the end, O(n) elsewhere | O(n), because the position must be found and elements shifted |
| Delete | O(n) | O(n) |
Finding the insertion point in a sorted array takes O(log n), but the shifting still costs O(n). The total is O(n). A common error is to claim that sorted insertion is O(log n).
Deleting by value in an unsorted array costs O(n) for the search plus O(n) for the shift. The total is still O(n).
Dynamic arrays and amortized cost
A fixed-size array cannot grow. A dynamic array, such as Python's list or C++'s vector, allocates extra capacity. When it fills up, it allocates a larger block, usually double the size, and copies every element over.
A single append that triggers a resize costs O(n). Resizes are rare. When the capacity doubles each time, the total copying over n appends is at most 1 + 2 + 4 + ... + n, which is less than 2n. So the amortized cost per append is O(1). Amortized cost is an average over a sequence of operations. It is not an average over random inputs, and the worst single append is still O(n).
Insertion in the middle remains O(n) even in a dynamic array, because of the shifting.
Two-dimensional arrays and index cost
Access to a[i][j] is also O(1). In row-major order, as used by C, the address is base + (i * cols + j) * size. Fortran uses column-major order: base + (j * rows + i) * size. GATE questions often give a base address and ask for the address of one element, so check which order is stated and whether indexing starts at 0 or 1.
Common errors
- Shifting in the wrong direction during insertion or deletion, which overwrites data.
- Forgetting the capacity check before insertion.
- Counting n shifts for deletion at index 0. The correct count is n - 1.
- Applying binary search to an unsorted array.
- Calling sorted insertion O(log n).
- Confusing amortized O(1) append with worst-case O(1).
Summary of costs
| Operation | Best | Worst | Notes |
|---|---|---|---|
| Access `a[i]` | O(1) | O(1) | Direct address arithmetic |
| Linear search | O(1) | O(n) | Any array |
| Binary search | O(1) | O(log n) | Sorted array only |
| Insert at end | O(1) | O(1) with spare capacity | Amortized O(1) if resizing |
| Insert at index | O(1) | O(n) | Shifts `size - pos` elements |
| Delete at index | O(1) | O(n) | Shifts `size - 1 - pos` elements |
Exercise
A sorted array holds 1000 elements and has spare capacity. You insert a new key so that the array stays sorted. The key belongs at index 400 (0-based). How many elements must shift, and what is the overall time complexity? Then state how many shifts deleting the element at index 400 from the original 1000-element array requires.
Show answer
Insertion at index 400 shifts the elements at indices 400 through 999, which is 1000 - 400 = 600 elements. Finding the position with binary search takes O(log n), but shifting dominates, so the overall time is O(n). Deleting the element at index 400 shifts the elements at indices 401 through 999, which is 1000 - 1 - 400 = 599 elements.
Exercise
A dynamic array doubles its capacity when full, starting at capacity 1. How many element copies occur in total during resizes when 16 elements are appended one at a time, and what is the amortized number of copies per append?
Show answer
Resizes happen when appending the 2nd, 3rd, 5th and 9th elements, with 1, 2, 4 and 8 elements copied. The total is 1 + 2 + 4 + 8 = 15 copies. Spread over 16 appends, this is 15 / 16, which is less than 1 copy per append, so appends are amortized O(1).