ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Data Structures & Algorithms (DSA)• 6 min read

Static vs Dynamic Arrays & Memory Layout

Contiguous memory, amortized O(1) resizing, capacity vs length

Arrays store elements in contiguous adjacent memory blocks, granting instant O(1) random access via index arithmetic: Address = Base + (Index * ElementSize).

Dynamic Array Resizing Mechanics

Static Array: Fixed size allocated at creation (like standard C or Java int[]).

Dynamic Array (like Python list or JavaScript Array): Automatically resizes when capacity is exhausted.

Geometric Growth: When an array with capacity 4 reaches full capacity, it allocates a new array of capacity 8 (doubling), copies all 4 items over, and frees the old array.

Amortized O(1): Although a resize takes O(n) to copy elements, it happens so infrequently that the average time per append operation is mathematically O(1).

Dynamic Array Insertion Cost
const arr = []; // initial capacity = 4

// O(1) fast appends into pre-allocated buffer
arr.push(10);
arr.push(20);
arr.push(30);
arr.push(40);

// Capacity reached! Next append triggers O(n) memory reallocation:
// 1. Allocate new memory block of size 8
// 2. Copy [10, 20, 30, 40]
// 3. Append 50
arr.push(50); // Amortized O(1)
Doubling strategy ensures appending remains amortized constant time.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What is the time complexity of looking up an element by index `arr[i]` in an array?