Arrays in Data Structures
An array is a block of contiguous memory holding elements of one type. That single property decides everything else about it: why arr[i] is O(1), why inserting at the front is O(n), and why almost every array interview question is really a question about moving indices cleverly.
Lessons in order
What you will be able to do
- An array is one contiguous block; the address of any element is computed, never searched for.
- Use an index loop when you need i, a for-each loop when you do not.
- Two pointers replaces a nested loop with one pass when order lets you rule out candidates.
- Consecutive windows overlap, so update the previous answer instead of recomputing it.
- Precompute once, answer many range queries in O(1) each.
Quiz yourself on Arrays
Reading is not recall. Take a timed quiz on this topic solo, or share a room code and battle friends on it.
⚡ Start the Arrays quizFrequently asked questions
Why is array access O(1) but linked list access O(n)?
An array computes an element's address with base + index x size, which is constant work. A linked list stores each node wherever memory is free and connects them with pointers, so reaching the nth node means following n links.
What is the difference between an array and an ArrayList?
An array has a fixed length set at creation and can hold primitives directly. An ArrayList wraps an array and reallocates a larger one when it fills, so it can grow — at the cost of some memory overhead and occasional copying.
Does an array always store elements of the same type?
In statically typed languages, yes, and that is what keeps the element size uniform. Python lists and JavaScript arrays appear to hold mixed types because they actually store references of uniform size, and the values themselves live elsewhere.
What is the time complexity of inserting into an array?
Appending to a dynamic array is O(1) amortised. Inserting at any other position is O(n), because every element after the insertion point must shift one place right.
Is it safe to modify an array while looping over it?
Removing elements during a forward loop shifts the remaining ones left and makes the loop skip an element. Either iterate backwards, or build a new array, or use the read/write two-index pattern.
How do I copy an array properly?
Assignment copies the reference, not the contents, so both names point at the same array. Use Arrays.copyOf in Java, list slicing or list.copy() in Python, the vector copy constructor in C++, or slice()/spread in JavaScript.