← All coursesDSA Foundations

Lesson 1 of 19

Array indexes

Imagine a row of numbered lockers. An array gives each item a position called an index. The first index is zero.

An index measures distance from the start

Index 0 means move zero places from the start. In an array with n items, the last index is n − 1. Reading a known position is cheap. Inserting into the middle of a packed array takes more work because the items after that position need to move.

Work through an example

A playlist holds [“Rain”, “Sun”, “Snow”]. You insert “Wind” at index 1. Which song now lives at index 2?

Step-by-step solution
  1. Before the edit, Rain is at 0, Sun is at 1 and Snow is at 2.
  2. Make room at index 1. Sun moves to 2 and Snow moves to 3.
  3. Put Wind at 1. Reading index 2 now gives Sun. A saved index can point to a different song after an edit.
JavaScript example
const songs = ["Rain", "Sun", "Snow"];
songs.splice(1, 0, "Wind"); // insert at 1, delete 0
songs[2]; // "Sun"
DSA compiler

Try it yourself

Finish the animation to unlock this question.

In [8, 3, 7, 4], which value lives at index 1?

Related exercise · Right Rotation · See this stage of the beginner path