Arrays: the workhorse of DSA
Arrays — the workhorse of DSA
In Python "array" usually means list. It's a dynamic contiguous buffer — index is O(1), append is amortized O(1), insert in the middle is O(n) (everything after shifts).
Patterns to have in your muscle memory
Prefix sum
Precompute cumulative sums once. Then any range sum is a subtraction. Turns O(n) range queries into O(1).
In-place two-pointer
Modify from both ends. Reverses, palindromes, partitioning without extra space.
Kadane's algorithm
Max subarray sum in O(n). Keep a running sum, reset to zero if it goes negative.
Common bugs to avoid
- Off-by-one on the end index.
range(n)is 0..n-1, not 0..n. - Modifying a list while iterating. Use
for x in list(seq):or build a new list. - Confusing
.copy()with slicing.a[:]is a shallow copy. Nested lists still share inner lists. list.remove(x)is O(n) and only removes the first match. Preferdel a[i]or list comprehension.
When a list is the wrong choice
- Frequent pop-from-front → use
collections.deque(O(1) both ends). - Fast membership check → use
set(O(1) avg). - Sorted numeric operations → use
sortedcontainers.SortedList.
Try it
- Given
nums = [3, 1, 4, 1, 5, 9, 2, 6], find the max subarray sum using Kadane's algorithm. - Write a function that returns the running average (each element = mean of it and everything before).
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Given
nums = [4, 2, 7, 1, 5], build a prefix-sum array soprefix[i]= sum ofnums[:i](soprefix[0] = 0). Then compute the sum ofnums[1..3]inclusive usingprefix[r + 1] - prefix[l]. Print the answer — expected10. - Exercise 2
Reverse
nums = [1, 2, 3, 4, 5]in-place using two pointers. No.reverse(), no slicing. Printnums— expected[5, 4, 3, 2, 1]. - Exercise 3
Given
nums = [3, 0, 6, 0, 4, 0, 1], move every zero to the end in-place while keeping the relative order of non-zeros. Printnums— expected[3, 6, 4, 1, 0, 0, 0].