Arrays
The most basic way to store an ordered list of items in memory.
What is it?
An array stores values side by side in memory, in order. If you know an item's position (its index), you can jump straight to it. Arrays are a building block for almost every other data structure.
Reading any item by index is very fast. Inserting or removing an item in the middle can be slow, because everything after it may need to shift.
Explain like I'm 10
An array is like a row of numbered parking spaces. Know the number and you walk straight to the car. But to add a car in the middle of a full row, every car after it must shift over one space.
Examples
Reading vs inserting
const arr = [10, 20, 30, 40];
console.log(arr[2]); // 30 — instant, O(1)
arr.splice(1, 0, 15); // insert 15 at index 1
// arr is now [10, 15, 20, 30, 40] — everything after index 1 had to shiftHow it works
Array elements sit in one continuous block of memory, so arr[i] is a direct calculation ("jump to this spot"): O(1).
Inserting or deleting anywhere but the end shifts every later element by one, which takes time proportional to the array's size: O(n).
Why does it exist?
Fast access by position matters for countless problems: searching, sorting, storing sequences of steps or events. Arrays are the default when order matters and you mostly read items rather than insert in the middle.
When to use it
Use an array when you need fast access by position and mostly read data: a leaderboard, a list of recent events, a lookup table by index.
When not to use it
If you often insert or remove items at the front or middle of a large collection, the O(n) shifting adds up. A linked list or another structure may fit better.
Common mistakes
Repeatedly inserting or removing items at the front of a large array, which is slower than it looks.
Assuming search by value is instant. Finding a value (not an index) still checks items one by one: O(n).
Forgetting that JavaScript arrays can hold mixed types, which is convenient but easy to misuse.
Practice exercises
- Easy:
Write a function that returns the largest number in an array.
- Medium:
Write a function that reverses an array without using the built-in
.reverse()method. - Hard:
Write a function that removes duplicate values from an array while preserving the original order.
Interview questions
Why is accessing an array by index O(1)?
Elements sit in contiguous memory, so any index's position is calculated directly, with no searching.
Why is inserting into the middle of an array O(n)?
Every element after the insertion point must shift over by one to make room.
When would you choose an array over a linked list?
When you need fast random access by index and rarely insert or remove items in the middle.
Why is `array.push()` described as *amortized* O(1) rather than plain O(1)?
Most pushes place the element in the next free slot: O(1). But the underlying storage has a fixed capacity. When it fills, the engine allocates a bigger block and copies every element: O(n) for that push. Capacity usually doubles, so copies get rarer and the average cost per push stays O(1).
Why is `array.pop()` O(1) but `array.shift()` (removing the first element) is O(n)?
pop() reads the last element and decrements the length; nothing moves. shift() leaves a gap at index 0, so every remaining element shifts one place left. That shifting grows with the array's size.
Why is `array.unshift()` O(n)?
To put a new element at index 0, every existing element must first shift one place right.
What does `[10, 20, 30, 40, 50].slice(1, 3)` return, and what's the time complexity of `slice`?
[20, 30]: from index 1 up to, but not including, index 3. It's O(k), where k is the number of elements copied (up to O(n) for the whole array).
What's the key difference between `.slice()` and `.splice()`?
.slice() returns a shallow copy of part of the array and leaves the original alone. .splice() changes the original in place, removing and/or inserting elements, and returns any removed elements.
Why is copying an array with `[...arr]` called a *shallow* copy?
It makes a new top-level array, but nested objects or arrays are copied by reference, not duplicated. The original and the copy share those nested objects, so changing one through either array affects both.
Why can't you reliably use `===` to check if two arrays contain the same values?
=== checks whether both sides are the same object in memory, not whether their contents match. So [1,2] === [1,2] is false. Compare element by element (or use a helper) instead.
What is the time complexity of `Array.prototype.sort()` in modern JavaScript engines?
O(n log n) in the average and worst case. Modern engines (e.g. V8) use hybrid comparison sorts like Timsort, and any comparison-based sort needs at least O(n log n) comparisons in the general case.
Why is binary search O(log n) while a plain search through an unsorted array is O(n) — and what does binary search require that the other doesn't?
Linear search doesn't know where the value is, so it may check every element. Binary search compares with the middle element and discards half the rest each step. That only works on a sorted array, which guarantees the target is in one particular half.
If you only need to search an array once, is it worth sorting it first so you can binary search?
No. Sorting costs O(n log n), more than one O(n) linear scan. It only pays off when you search the same array many times, spreading the sort cost across many O(log n) searches.
What's the time and space complexity of reversing an array in place with two pointers (one at each end, swapping and moving inward)?
O(n) time, since each element is visited once. O(1) extra space, since swaps happen inside the existing array.
What's wrong with this loop meant to print every element of an array — `for (let i = 0; i <= arr.length; i++) { console.log(arr[i]); }`?
It's an off-by-one bug. With <=, i reaches arr.length, one past the last valid index (arr.length - 1), so the last pass logs undefined. Use i < arr.length.
Why does `delete arr[2]` behave differently from `arr.splice(2, 1)`?
delete removes the value but leaves an empty hole (reads as undefined), without shifting later elements or changing .length. splice removes the element, shifts later elements left and shrinks .length by one.
What's the time complexity of merging two arrays with `.concat()` or the spread operator?
O(n + m), where n and m are the two lengths. A new array is built and every element from both is copied in.
What's the time complexity of finding the maximum value in an unsorted array versus in an array already sorted ascending?
Unsorted: O(n), since any element could be the maximum. Sorted ascending: O(1), since the maximum is the last element.
If you need to repeatedly check whether values exist in a collection, why might converting the array to a `Set` first be worth it?
array.includes() is O(n) per check. Building a Set costs O(n) once, then each lookup is O(1) on average thanks to hashing. With many lookups, the one-time cost quickly pays off.
For the classic "two sum" problem (find two numbers in an array that add up to a target), what's the time and space complexity of a brute-force approach versus a hash-map approach?
Brute force checks every pair with nested loops: O(n²) time, O(1) extra space. The hash-map approach makes one pass, checking whether target - number was already seen: O(n) time, O(n) space. It trades memory for speed.
For a 2D array (an array of arrays) representing a grid, what's the time complexity of accessing `grid[i][j]`?
O(1). grid[i] jumps to the row and [j] jumps to the element. Two O(1) steps are still O(1), whatever the grid's size.
What's the space complexity of a 2D array with n rows and m columns?
O(n × m): one slot for every row-column pair, so space grows with the product of the dimensions, not their sum.
A `for` loop and `.forEach()` are both O(n) to iterate an array — so why might the plain loop run measurably faster?
Big O ignores the constant cost per step. .forEach() calls a callback on every iteration, which adds overhead a plain loop doesn't have. Both are O(n) with different constant factors.
Are `Array.isArray()` and reading `.length` ever more expensive than O(1)?
No, both are O(1). .length is kept up to date automatically rather than recounted, and Array.isArray() checks the object's internal type tag, not its contents.
Both arrays and linked lists take O(n) to fully traverse — so why do arrays tend to iterate faster in practice?
Array elements sit in one contiguous block, so the CPU cache can pre-fetch what comes next. Linked list nodes can be scattered across memory, so each step may be a slower, uncached access. Same Big O, different constant factor.
What's the time complexity of rotating an array left by one position by removing the first element and pushing it to the end?
O(n). shift() is O(n) because every element moves left, and push() is amortized O(1). The shift dominates.
Finding duplicate values in an unsorted array with nested loops is O(n²) — how does using a hash set reduce that to O(n)?
Nested loops compare every element with every other, about n² comparisons. With a hash set, you make one pass and check whether each element is already in the set (O(1) average) before adding it. That's O(n) time, at the cost of O(n) extra space.
What's the worst-case time complexity of `array.indexOf()`, and when does that worst case happen?
O(n), when the target is the last element or isn't in the array, so every element is checked.
Pushing n elements one at a time versus preallocating an array of size n and assigning by index — do they have different time complexity?
No, both are O(n). Each push is amortized O(1), and each indexed assignment is O(1). Preallocating can avoid some occasional O(n) resize-and-copy steps, which may lower the constant factor, but the complexity is the same.