Module 2 · Lesson 1

Arrays and Dynamic Arrays

Learn how arrays store data in contiguous memory and how dynamic arrays grow automatically.

Audio: Arrays and Dynamic Arrays
0:000:00

Arrays and Dynamic Arrays

Arrays are the most fundamental data structure in programming. They store elements in a contiguous block of memory, which means accessing any element by index is incredibly fast.

What is an Array?

An array is an ordered collection of elements where each element has a numeric index starting from 0:

| Index | 0 | 1 | 2 | 3 | |-------|---|---|---|---| | Value | "apple" | "banana" | "cherry" | "date" |

Static vs Dynamic Arrays

  • Static arrays (C-style): Fixed size, declared at creation. Cannot grow or shrink.
  • Dynamic arrays (Python list, JS array, C++ vector, Java ArrayList): Automatically resize when you add/remove elements.

Time Complexity

| Operation | Time | |-----------|------| | Access by index | O(1) | | Search (unsorted) | O(n) | | Append to end | O(1) amortized | | Insert at position | O(n) | | Remove at position | O(n) |

Accessing by index is instant because the computer can calculate exactly where in memory the element lives. But inserting or removing in the middle requires shifting all subsequent elements.

When to Use Arrays

Arrays are your default choice when you need:

  • Fast access by position
  • Simple iteration over all elements
  • A collection that mostly grows at the end

Try It Yourself

  • Create an array of 5 numbers, then print their sum
  • Write code to find the maximum value in an array
  • Reverse an array without using a built-in reverse function

Code Playground

Edit the code below and click Run to see the output. Switch between languages using the tabs.

Loading editor...