Array Basics
Build fluency with arrays — the most fundamental data structure. Learn creation, traversal, mutation, and the built-in methods you will use in every coding problem.
Learn & Reference
Understanding the Pattern
Array Basics
Arrays are the backbone of almost every coding problem. Whether the input is a list of numbers, a sequence of characters, or a collection of objects, you need to be comfortable creating, reading, modifying, and iterating over arrays before tackling any algorithmic pattern.
Core Operations
Creation & Access
Create arrays of fixed or dynamic size. Access elements by zero-based index. Know how to get the length, first element, and last element in your language.
Traversal
Iterate forward, backward, or with index tracking. Use for, for...of, forEach, or enumerate/range depending on what you need (index, value, or both).
Mutation
Add/remove elements at the beginning, end, or middle. Know the difference between methods that mutate in place vs. return a new array.
Search & Filter
Find elements, check existence, filter by condition. Know when to use built-in methods vs. manual loops.
Key Principles
- Zero-based indexing — the first element is at index 0, the last is at
length - 1 - Bounds checking — always verify index is within
[0, length)before access - In-place vs. copy — some methods mutate the original array; others return a new one. Know which is which in your language
- Contiguous memory — arrays have O(1) random access but O(n) insertion/deletion in the middle
Common Problem Patterns
- Linear scan — single pass to find max/min, count, or accumulate
- Two-pass — first pass collects info, second pass builds result
- In-place swap — rearrange elements without extra space using index swaps
- Prefix computation — running sum/product as you iterate
Common Mistakes
- Off-by-one errors: Array of length n has valid indices 0 to n-1, not 1 to n
- Modifying while iterating: Adding/removing elements during a loop causes skipped elements or infinite loops — iterate over a copy or use indices carefully
- Forgetting empty array check: Operations like
arr[0]orMath.max(...arr)fail on empty arrays - Confusing slice vs. splice: In JavaScript,
slicecopies,splicemutates. Similar distinctions exist in other languages - Not considering negative numbers: Algorithms that assume positive values (like using array indices as markers) break with negatives
When to Use
Template
1# --- Linear Scan (find max) ---2def find_max(arr):3result = arr[0]4for num in arr:5result = max(result, num)6return result78# --- Build Result Array ---9def transform(arr):10result = []11for num in arr:12result.append(num * 2)13return result1415# --- In-Place Swap ---16def swap(arr, i, j):17arr[i], arr[j] = arr[j], arr[i]1819# --- Two-Pointer Technique ---20def reverse_in_place(arr):21left, right = 0, len(arr) - 122while left < right:23arr[left], arr[right] = arr[right], arr[left]24left += 125right -= 126return arr
Syntax Reference
1# === Creation ===2arr = [] # empty list3arr = [1, 2, 3] # literal4arr = [0] * n # n zeros5arr = list(range(1, 6)) # [1, 2, 3, 4, 5]67# === Access ===8arr[0] # first element9arr[-1] # last element10len(arr) # length11arr[1:4] # slice [1, 2, 3] (end exclusive)1213# === Add / Remove ===14arr.append(x) # add to end: O(1)15arr.insert(i, x) # insert at index: O(n)16arr.pop() # remove last: O(1)17arr.pop(i) # remove at index: O(n)18arr.remove(x) # remove first occurrence: O(n)1920# === Search ===21x in arr # contains: O(n)22arr.index(x) # index of first x (ValueError if missing)23arr.count(x) # count occurrences2425# === Transform ===26arr.reverse() # reverse in place27arr[::-1] # reversed copy28arr.sort() # sort in place29sorted(arr) # sorted copy30arr.extend(other) # append all from other3132# === Functional ===33list(map(fn, arr)) # map34list(filter(fn, arr)) # filter35sum(arr) # sum36min(arr), max(arr) # min, max
Common Recipes
1# --- Find Max and Min ---2def find_max_min(arr):3return [max(arr), min(arr)]45# --- Reverse In Place ---6def reverse_array(arr):7left, right = 0, len(arr) - 18while left < right:9arr[left], arr[right] = arr[right], arr[left]10left += 111right -= 112return arr1314# --- Move Zeros to End ---15def move_zeros(arr):16write = 017for read in range(len(arr)):18if arr[read] != 0:19arr[write], arr[read] = arr[read], arr[write]20write += 121return arr2223# --- Running Sum ---24def running_sum(arr):25result = []26total = 027for num in arr:28total += num29result.append(total)30return result3132# --- Merge Two Sorted Arrays ---33def merge_sorted(a, b):34result = []35i = j = 036while i < len(a) and j < len(b):37if a[i] <= b[j]:38result.append(a[i]); i += 139else:40result.append(b[j]); j += 141result.extend(a[i:])42result.extend(b[j:])43return result
Complexity
| Operation | Time | Notes |
|---|---|---|
| Access by index | O(1) | Direct memory offset |
| Push / Append | O(1)* | Amortized — occasional resize |
| Pop (end) | O(1) | Remove last element |
| Insert (middle) | O(n) | Must shift elements right |
| Delete (middle) | O(n) | Must shift elements left |
| Search (unsorted) | O(n) | Linear scan |
| Search (sorted) | O(log n) | Binary search |
| Sort | O(n log n) | Built-in sort algorithms |
Watch Out
- ✗Off-by-one errors: Array of length n has valid indices 0 to n-1, not 1 to n
- ✗Modifying while iterating: Adding/removing elements during a loop causes skipped elements or infinite loops — iterate over a copy or use indices carefully
- ✗Forgetting empty array check: Operations like `arr[0]` or `Math.max(...arr)` fail on empty arrays
- ✗Confusing slice vs. splice: In JavaScript, `slice` copies, `splice` mutates. Similar distinctions exist in other languages
- ✗Not considering negative numbers: Algorithms that assume positive values (like using array indices as markers) break with negatives