1. University MCA (AI/ML) Semester 2
  2. CAP7004
  3. Unit 2

CAP7004 · Unit 2: Linear data structures

Arrays and dynamic lists

8 practice questions

Key points

  • Array index access is O(1)
  • Python list is a dynamic array; append is amortized O(1)
  • Insert or delete in the middle shifts elements: O(n)
  • Slicing copies; build 2D lists with comprehensions

An array stores elements in contiguous memory, so index i is reached directly: a[i] is O(1).

Python's list is a dynamic array of references. When it is full, it allocates a larger block and copies the elements. Growing the capacity geometrically (roughly doubling) makes append amortized O(1): the occasional O(n) copy is spread over many cheap appends. Copying costs for 8 appends starting at capacity 1 total 7 element copies.

OperationCost
a[i], a[i] = xO(1)
append(x), pop()O(1) amortized / O(1)
insert(i, x), remove(x), pop(i)O(n) (shifts elements)
x in a, index(x)O(n)
a[i:j]O(j - i), makes a new list
a + bO(len(a) + len(b))

2D arrays: build rows with a comprehension, [[0]*c for _ in range(r)], never [[0]*c]*r.

Exam pitfall: amortized O(1) is not worst-case O(1); one append can still take O(n).

Try two questions

Question 1 · Tier 2, Understand

Why is append amortized O(1) in a dynamic array?

  1. Capacity grows geometrically, so copying is spread over many appends
  2. Every append copies exactly one element into place
  3. Python never needs to copy elements when growing
  4. Lists are stored as chains of linked nodes
Show the answer

A. Rare resize copies average out to a constant cost per append.

Question 2 · Tier 3, Apply

x = list(range(10)); y = x[2:5]; y[0] = 99. What is x[2]?

  1. An error
  2. 99
  3. 5
  4. 2
Show the answer

D. Slicing creates a new list, so changing y does not change x.