Skip to content
  • Open the math solver
  • Ask the AI tutor
  • Find an AP course
  • Create a quiz
  • Open the calculator
  • Graphing Calculator
  • Browse all calculators
  • Read math guides
↑ ↓Enter to open · Esc to close
Solve a problem
Data StructuresData StructuresCollege

Arrays and Lists

Indexing, traversal and dynamic arrays.

An array stores a sequence of values in consecutive memory, so any element can be reached instantly by its index. Most languages count from 0, so an array of length nn has indices 00 to n−1n - 1. Reading or writing `a[i]` takes constant time, which is the array's great strength.

The cost comes with inserting or deleting in the middle, which shifts every later element. Dynamic arrays (Python lists, Java ArrayList, JavaScript arrays) grow automatically by allocating a larger block and copying, which keeps appends fast on average. Linked lists make insertion cheap but give up instant indexing.

Key ideas

  • Index access: O(1)O(1); search an unsorted array: O(n)O(n).
  • Insert or delete in the middle: O(n)O(n) because of shifting.
  • Appending to a dynamic array is O(1)O(1) amortised.
  • Traverse with a loop over indices 00 to n−1n - 1.

Worked example

An array holds `[4, 9, 2, 7, 5]`. What are `a[1]`, `a[4]` and the sum of all elements?

  1. Indices start at 0: `a[0] = 4`, so `a[1] = 9`.
  2. The last index is 5−1=45 - 1 = 4: `a[4] = 5`.
  3. Sum: 4+9+2+7+5=274 + 9 + 2 + 7 + 5 = 27.

Answer: `a[1] = 9`, `a[4] = 5`, sum 2727

Common mistakes

  • Accessing index nn, one past the end.
  • Modifying a list while looping over it.
  • Assuming insertion at the front is as cheap as appending.

Practice questions

Try each one, then open the answer. Numerical answers on this page are verified by an automated calculation check.

  1. 1.What is the last valid index of an array of length 12?

    Show answer

    1111

  2. 2.Average of `[3, 8, 10, 15]`.

    Show answer

    99

  3. 3.Inserting at index 0 of a 1000-element array shifts how many elements?

    Show answer

    10001000

More in Data Structures