Arrays

The most fundamental data structure — contiguous memory, O(1) indexing, and why it powers almost everything else.

Beginner 5 min readLesson 1 of 16 Interview Q&A

An array stores elements of the same size in one contiguous block of memory. That single property — elements sitting side by side — is what makes arrays the fastest structure for indexed access and the building block for strings, heaps, hash tables, matrices and dynamic arrays.

4207119233884215arr[2]
An array of 6 integers. arr[2] is computed directly — no scanning.

Why indexing is O(1)

Because elements are contiguous and equally sized, the address of any element is a single multiplication and addition:

address(arr[i])=base+i×elementSize\text{address}(arr[i]) = \text{base} + i \times \text{elementSize}

For an int[] starting at address 0x1000 with 4-byte ints, arr[3] lives at 0x1000 + 3 × 4 = 0x100C. The CPU computes that in one instruction, no matter how large the array.

420x100070x1004190x100830x100C880x1010210x1014
Each int occupies 4 bytes; arr[3] is at base + 12.

Operations and their cost

OperationTimeWhy
Access arr[i]O(1)Address arithmetic
Update arr[i] = xO(1)Address arithmetic
Search (unsorted)O(n)Must check each element
Search (sorted)O(log n)Binary search
Insert / delete at endO(1)**Amortized for dynamic arrays
Insert / delete at index iO(n)Elements after i must shift

Inserting in the middle is expensive because every later element moves one slot:

100201→2303404505
Inserting at index 2 shifts 30, 40, 50 right by one — O(n) work.

Static vs dynamic arrays

A static array has a fixed size chosen at creation (int[] a = new int[10] in Java, int a[10] in C). A dynamic array — Java ArrayList, Python list, JavaScript Array, C++ vector — grows automatically.

How a dynamic array grows

It keeps a backing static array with spare capacity. When it is full, it allocates a new array (typically 1.5× or 2× larger), copies everything over, and frees the old one.

  1. size = 4, capacity = 4 — the array is full.
  2. append(x) triggers a resize: allocate capacity 8.
  3. Copy the 4 existing elements — O(n) for this one append.
  4. Write x at index 4. The next 3 appends are O(1) again.

Code

import java.util.*;

int[] fixed = new int[5];          // static: zero-initialised, fixed length
int[] primes = {2, 3, 5, 7, 11};
System.out.println(primes[2]);     // 5 — O(1)

List<Integer> list = new ArrayList<>();   // dynamic array
list.add(10);                      // amortized O(1)
list.add(0, 5);                    // O(n): shifts everything right
list.remove(list.size() - 1);      // O(1): remove from end
Collections.sort(list);            // O(n log n)

// 2D array: an array of arrays (rows can differ in length)
int[][] grid = new int[3][4];
grid[1][2] = 9;

Multidimensional arrays

A 2D array m[r][c] with R rows and C columns is usually stored in row-major order (C, Java, Python/NumPy default): row 0, then row 1, and so on.

index(r,c)=r×C+c\text{index}(r, c) = r \times C + c
0123012123456789101112
m[1][2] = 7 → flat index 1×4 + 2 = 6

Common techniques

Most array problems are solved with a handful of patterns — each has a full lesson in Coding Patterns:

Pitfalls

  • Off-by-one errors. Valid indices are 0 … n-1. Loops use i < n, not i <= n.
  • Aliasing. Assigning an array copies the reference, not the data. Use Arrays.copyOf, list.copy() / slicing, or [...arr] / structuredClone.
  • Removing while iterating shifts indices under you. Iterate backwards, or build a new array.
  • Front insertion in a loop is O(n²). Append then reverse, or use a deque.
Key takeaways
  • Arrays are contiguous: O(1) indexed access via base + i × size, and excellent cache locality.
  • Insert/delete in the middle is O(n) because elements shift.
  • Dynamic arrays grow geometrically, giving amortized O(1) append.
  • 2D arrays are usually row-major; iterate rows in the outer loop.
Interview questions
QWhy is accessing arr[i] O(1) but finding a value O(n)?easy

Access uses the index to compute the memory address directly. Finding a value requires comparing against elements because the value gives no information about its position — unless the array is sorted, which enables O(log n) binary search.

QArrayList vs LinkedList in Java — which would you choose?medium

Almost always ArrayList. It has O(1) random access, amortized O(1) append, and far better cache locality. LinkedList only wins for frequent insertions/removals through an iterator in the middle of a huge list — and even then, the pointer-chasing cost often makes ArrayList faster in practice. For queue/deque usage, prefer ArrayDeque.

QWhat growth factor should a dynamic array use, and why not grow by a constant?medium

Growing by a constant k makes n appends cost O(n²/k) total — O(n) amortized per append. Any geometric factor (1.5×, 2×) gives amortized O(1). Smaller factors waste less memory; 1.5× also lets the allocator reuse freed blocks. Java's ArrayList uses 1.5×, CPython ~1.125× plus a constant, many C++ libraries 2×.

QRotate an array by k positions in O(1) extra space.medium

Reverse the whole array, then reverse the first k elements and the remaining n−k separately (with k %= n). Each element moves exactly twice: O(n) time, O(1) space.